patternjavascriptMajor
Set of jQuery .onclick functions
Viewed 0 times
functionsjquerysetonclick
Problem
I am hiding and fading in different content on the same page using jQuery to
It works how I want it to, but the way I've written the jQuery looks like it could be simplified.
Here's a jfiddle
How can I rewrite the jQuery so it does exactly the same thing but in much less code?
hide() and fadeIn() the content depending on which link is clicked.It works how I want it to, but the way I've written the jQuery looks like it could be simplified.
$("#navItem1").on('click', function(){
$('#content-wrap1').hide();
$('#content-wrap2').hide();
$('#content-wrap3').hide();
$('#content-wrap4').hide();
$('#content-wrap5').hide();
$('#content-wrap1').fadeIn(1000);
});
$("#navItem2").on('click', function(){
$('#content-wrap1').hide();
$('#content-wrap2').hide();
$('#content-wrap3').hide();
$('#content-wrap4').hide();
$('#content-wrap5').hide();
$('#content-wrap2').fadeIn(1000);
});
$("#navItem3").on('click', function(){
$('#content-wrap1').hide();
$('#content-wrap2').hide();
$('#content-wrap3').hide();
$('#content-wrap4').hide();
$('#content-wrap5').hide();
$('#content-wrap3').fadeIn(1000);
});
$("#navItem4").on('click', function(){
$('#content-wrap1').hide();
$('#content-wrap2').hide();
$('#content-wrap3').hide();
$('#content-wrap4').hide();
$('#content-wrap5').hide();
$('#content-wrap4').fadeIn(1000);
});
$("#navItem5").on('click', function(){
$('#content-wrap1').hide();
$('#content-wrap2').hide();
$('#content-wrap3').hide();
$('#content-wrap4').hide();
$('#content-wrap5').hide();
$('#content-wrap5').fadeIn(1000);
});
function fadeInFirstContent(){
$('#content-wrap1').fadeIn(1000);
}
fadeInFirstContent();Here's a jfiddle
How can I rewrite the jQuery so it does exactly the same thing but in much less code?
Solution
Perhaps change the HTML:
Navitem:
The content
jQuery
Navitem:
The content
jQuery
$('.navItem').on('click',function(){
$('.content-wrap').hide();
$('#content-wrap'+$(this).data('content-id')).fadeIn(1000);
});Code Snippets
<span class="navItem" data-content-id="1"></span><div id="content-wrap1" class="content-wrap"></div>$('.navItem').on('click',function(){
$('.content-wrap').hide();
$('#content-wrap'+$(this).data('content-id')).fadeIn(1000);
});Context
StackExchange Code Review Q#26229, answer score: 31
Revisions (0)
No revisions yet.