Reputation: 738
Im having some menu objects, here "link1" and "link2" which I want to toggle some content (forms) on my webpage.
If form1 is visible and I click link2, I want form1 to close and form2 to open.
Relevant jQuery:
$('#link1').click(function(){
$('#form1:visible').hide();
$('#form2:visible').hide();
$('#form1:hidden').show();
});
$('#link2').click(function(){
$('#form1:visible').hide();
$('#form2:visible').hide();
$('#form2:hidden').show();
});
Question: How can I make this simpler?
Upvotes: 0
Views: 216
Reputation: 1873
I don't know if i got you right, but you have href links, and so when u click link2 you want to open form2 (in case it is not already open), and same process for link1 and form1 ?
what u can do is give a css class for each form and an id , and then:
$('#link1').click(function(){
$('#idOform1').css("display","block");
$('#idOform2').css("display","none");
});
$('#link2').click(function(){ $('#idOform2').css("display","block"); $('#idOform1').css("display","none"); });
Upvotes: 0
Reputation: 522005
$('#link1').click(function(){
$('#form2').hide();
$('#form1').show();
});
$('#link2').click(function(){
$('#form1').hide();
$('#form2').show();
});
It hardly gets any simpler. If there's any correlation between the link clicked and the form, like the 1
and 2
in the name, you could condense it into a single function that dynamically gets the right form and shows it... Whether that's any simpler is debatable though:
$('#link1, #link2').click(function () {
$('form').hide();
$('#form' + this.id.substr(-1)).show();
});
Upvotes: 2
Reputation: 77251
In the HTML:
<form id="form1" class="form_group1" ... >
<form id="form2" class="form_group1" ... >
...
<form id="formN" class="form_group2" ... >
In javascript:
$('#link1').click(function(){
$('.form_group1').hide();
$('.form_group2').show();
});
$('#link2').click(function(){
$('.form_group2').hide();
$('.form_group1').show();
});
Upvotes: 0
Reputation: 50095
You can use the toggle
function which will switch the element between the visible and hidden states:
var f1 = $('#form1'), f2 = $('#form2');
$('#link1').click(function(){
f1.toggle();
f2.hide();
});
$('#link2').click(function(){
f1.hide();
f2.toggle();
});
Otherwise, caching the two #form
selector will help make it slightly more better.
Upvotes: 3