How to get element by ID based on href link with jQuery?
I'm trying to fade out in a hidden element based on an attribute of a href
clicked link, but I can't figure out how, I've tried this:
http://jsfiddle.net/vengiss/Zhn2W/
But somehow it $(textBlock)
just returns an empty object.
Thanks in advance!
source to share
You use this
(which refers to the anchored anchor) instead of the intended element to find text blocks. Use a selector instead #text-blocks > div
:
// Fade out any visible text blocks
$('#text-blocks > div').fadeOut('normal', function() {
// Fade in selected text block
$(textBlock).fadeIn();
});
This is a working jsfiddle .
EDIT:
Also, you may need to avoid inserting and excluding an already selected element and in this 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.
source to share
Try the following:
$('a[href="ABC"]').fadeIn();
Selection documentation can be found at http://docs.jquery.com/Selectors
For attributes:
= exactly equal
! = not equal
^ = starts with
$ = ends with
* = contains
source to share
The problem with the code you are using now is pretty simple. The selector you use to find the delimiters will be:
$(this).find('div')
But in this context this
refers to the element that was clicked. Just change this selector to:
$('#text-blocks').find('div')
And it should work.
EDIT: Something else I noticed regarding your wrapper function. You missed the open-ended parentheses so that none of your codes ever run. Alternatively, to run it on a finished document, you can add jQuery (or $
) to the very beginning of the code.
source to share
The problem was that you forgot to add the first one $
to the prepared jQuery 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 - here .
source to share