3

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!

Javier Villanueva
  • 3,886
  • 13
  • 48
  • 80

4 Answers4

1

Try this:

$('a[href="ABC"]').fadeIn();

Selector documentation can be found at http://docs.jquery.com/Selectors

For attributes:

= is exactly equal

!= is not equal

^= is starts with

$= is ends with

*= is contains

Select <a> which href ends with some string

Community
  • 1
  • 1
msigman
  • 4,474
  • 2
  • 20
  • 32
  • Not really trying to fade in the link but the div, eg. if I click the link with href `#text1` I want to fade in the div with id `text1`. Since the href already includes the `#` symbol I thought I could pass it to the jQuery function to select it :( – Javier Villanueva Mar 31 '12 at 19:15
1

The issue with the code you're currently using is pretty simple. The selector you use to find the divs to fade out is:

$(this).find('div')

But in that context this refers to the element that was clicked on. Simply change that selector to:

$('#text-blocks').find('div')

And it should work.

EDIT: Something else I noticed regarding your wrapper function. You missed the open-close parenthesis off the end, so none of your code is ever run. Alternatively to have it run on document ready you could prepend jQuery (or $) to the very start of the code.

MartinAnsty
  • 383
  • 2
  • 9
1

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.

Alexander
  • 23,432
  • 11
  • 63
  • 73
  • Great that fixed the issue thanks, now I have to figure out why the div sometimes fades in twice really quick, any ideas? I updated your fiddle to better reflect how I'm actually using it http://jsfiddle.net/vengiss/Zhn2W/13/ – Javier Villanueva Mar 31 '12 at 19:22
1

The problem was that you forgot to add the first $ in the jQuery ready call. This is the JavaScript you need:

$(function(){
    $('#links a').on('click', function(e) {
        e.preventDefault();

        // Fade out any visible text blocks
        $('#text-blocks div').fadeOut();

        // Fade in required one
        $($(this).attr('href')).fadeIn(); 

    });        
});​

jsFiddle is here.

hohner
  • 11,498
  • 8
  • 49
  • 84