Search code examples
jquerydomhreffadein

How to get an element by ID based on a link's href with jQuery?


I'm trying to fade in a hidden element based on the href attribute of a clicked link but I can't figure out how, I tried this:

http://jsfiddle.net/vengiss/Zhn2W/

But for some reason $(textBlock) just returns an empty object.

Thanks in advance!


Solution

  • You are using this (which refer to the clicked anchor) instead of the intended element to find the text blocks. Try using #text-blocks > div selector instead:

    // Fade out any visible text blocks
    $('#text-blocks > div').fadeOut('normal', function() {
      // Fade in selected text block
      $(textBlock).fadeIn(); 
    });    
    

    This is a working jsfiddle of it.

    EDIT:

    Also you may want to avoid fadding in and out the already chosen element and in that case use .not():

    // Fade out any visible text blocks
    $('#text-blocks > div').not(textBlock).fadeOut('normal', function() {
      // Fade in selected text block
      $(textBlock).fadeIn(); 
    });
    

    This is a working jsfiddle of this edition.