I'm trying to get my jquery to select a different element based on a value stored in the clicked elements attribues. But it keeps animating the clicked element. Because there are multiple classes named element1 I figured this would be the easiest way to animate a specified div associated with that button.
$(".element1").click(function(){
var expander = $(this).attr("id");
var expander2 = '#' + expander;
test(expander2);
});
function test(expander3) {
if (toggle == true) {
$(expander3).animate({height:200}, {queue:false}, "slow");
$(expander3).animate({width:400}, {queue:false}, "slow");
toggle = false;
} else if (toggle == false) {
$(expander3).animate({height:0}, {queue:false}, "slow");
$(expander3).animate({width:50}, {queue:false}, "slow");
toggle = true;
}
}
I did alert(expander2) and I'm getting the correct id (i.e. #id1, #id2 etc etc) but it is only animating the .element1, .element2 etc etc. It's like it's ignoring the correct id.
Here's how the html looks if that helps:
<input type="button" id="id1" class="element1" value="TextGoesHere"></input>
<div id="id1">
This should be animating.
</div>
Your html is invalid: the id
attribute should be unique. When you try to select by id
with $("#idThatIsNotUnique")
it will just find the first element (or potentially the last element in some browsers) with that id
- in your case the input, not the div.
You could use an html5 data-
attribute instead:
<input type="button" data-animate-id="id1" class="element1" value="TextGoesHere"></input>
<div id="id1">This should be animating.</div>
And then JS:
$(".element1").click(function(){
var expander = $(this).attr("data-animate-id");
var expander2 = '#' + expander;
test(expander2);
});