Reputation: 1565
Here is a simple question for a jQuery guru.
A work fiddle you can find HERE
As you can see there is a container with id="hideme"
. I want when I click on link2
this id
to hide, but with condition that when I click on link1
or link3
it must become visible again.
So I thought it must be } ELSE {
or it is not possible in jQuery?
$('#link2').click(function(){
if(jQuery('#link2').data('clicked')) {
$('#hideme').hide();
} else {
$('#hideme').show();
};
});
Upvotes: 0
Views: 92
Reputation: 1751
There is no need to use else statements this way as jQuery is very tunnel-visioned in it's event-binding. Bind some event to some element and that will happen. If you want another event to happen in another case, simply define it as such. That being said you CAN use javascript statements in jQuery like so:
if(x = 0)
{
$("div").hide();
}
else
{
$("div").show();
}
But in this instance you are using a logical operator against some external variable. When binding an event this is entirely unnecessary. Try taking a look at the toggle() feature. Here's a simple example:
$("#id").click(function() {
$("#MyDiv").toggle();
});
Upvotes: 0
Reputation: 7352
Cannot be done by binding an event to '#link2', but can be done in two different other ways :
$('#link2').click(function(){
$('#hideme').hide();
});
$('#link1, #link3').click(function(){
$('#hideme').show();
});
or
$('ul a').click(function() {
if ($(this).attr('id') == 'link2') {
$('#hideme').hide();
}
else {
$('#hideme').show();
}
});
Upvotes: 0
Reputation: 148110
You need to bind click
event to all links and apply condition in handler
.
$('[id^=link]').click(function () {
if (this.id == 'link2') $('#hideme').hide();
else if (this.id == 'link1' || this.id == 'link2') $('#hideme').show();
});
Upvotes: 0
Reputation: 10658
Your click
listener is only attached to #link2
. You want to detect when any of the links are clicked, then do your test. Like so:
$('a').click(function(){
if(this.id === 'link2') {
$('#hideme').hide();
} else {
$('#hideme').show();
};
});
Upvotes: 2
Reputation: 37533
You need to bind the separate events:
$('#link2').click(function() {
$('#hideme').hide();
});
$('#link1, #link3').click(function() {
$('#hideme').show();
});
I would actually make link1 and link3 have a common class to make selection "simpler".
Upvotes: 0