Search code examples
mootoolsmootools-more

Reveal div when link is clicked


Using mootools.js 1.3.2 and mootools-more.js

As far as I can tell this is supposed to reveal the div and also hide the content and linkTab divs at the same time.

$('blogLink').addEvent('click', function(){
 $('homeLink').removeClass('active'); 
 $('linkTab').removeClass('active'); 
 $('blogLink').addClass('active');  
 content.slideOut();
 linkTab.slideOut();
 blogLink.slideIn();
});

This is the HTML

<a href="#" id="blogLink">Blog</a>
<div id="blogContent">
content here
</div>

It all works properly and that's OK but in addition to this, I also want to be able to give people a URL like http://mysite.com/#blogLink and have that blogContent div opened. When I do that now, it takes me to the top of the page and the blogContent div is hidden.

How do I do achieve that? I did try adding the mootools-smoothscroll.js and using the method outlined here http://davidwalsh.name/smooth-scroll-mootools but that just broke the entire page - would not load properly.

I have zero experience with mootools and weak on Javascript so please excuse me if I take a while to 'get' what you're trying to explain.

Many thanks.


Solution

  • First, are you particularly attached to MooTools? If you're a JavaScript newbie, jQuery is probably easier to use and definitely has a larger support community. But I'll post a solution that should work in MooTools for now:

    If I understand you correctly, what you want to achieve is the following:

    • The anonymous function you posted will run when "Blog" is clicked
    • The function will also run if someone visits the page with #blogLink in the URL.

    That's not too difficult to achieve:

    // Once the DOM has loaded - so that our elements are definitely available
    window.addEvent('domready', function() {
        // Check for #blogLink hashtag, and reveal blog
        if(window.location.hash == 'blogLink') { revealBlog(); }
    
        // Make sure blog is revealed when link is clicked
        $('blogLink').addEvent('click', revealBlog);
    });
    
    function revealBlog() {
        $('homeLink').removeClass('active'); 
        $('linkTab').removeClass('active'); 
        $('blogLink').addClass('active');  
        content.slideOut();
        linkTab.slideOut();
        blogLink.slideIn();
    }
    

    You could also change your link mark-up to:

    <a href="#blogLink" id="blogLink">Blog</a>
    

    To make sure they're always on the correct link when the blog is revealed.