I want to make something like a menu so each menu item contain different content, but I do not want page reload. So I've made something like this.
$(document).ready(function() {
var $hide = $('div#hide'),
$home = $('div.home'),
$download = $('div.download'),
$about = $('div.about'),
$contact = $('div.contact');
$hide.css('display', 'none');
$('a.home').on('click', function() {
$hide.fadeOut();
$home.delay(300).fadeIn(2000);
});
$('a.download').on('click', function() {
$hide.fadeOut();
$download.delay(300).fadeIn(2000);
});
$('a.about').on('click', function() {
$hide.fadeOut();
$about.delay(300).fadeIn(2000);
});
$('a.contact').on('click', function() {
$hide.fadeOut();
$contact.delay(300).fadeIn(2000);
});
});
Now... I believe that this could be way more cleaner and simplified but I cannot think of anything. I am basically new into jQuery...
Everything works fine, however I have two questions. 1) Can you make this script cleaner a bit? 2) Can you tell me how to load content simultaneously... Currently when home is loaded and I click download, it sort of jump while fadeIn...
You can use preventDefault()
method of the event
object which prevents the default action of the event.
$('a.home, a.download, a.about, a.contact').on('click', function(event) {
event.preventDefault();
var cls = this.className;
$hide.fadeOut();
$('.'+cls).delay(300).fadeIn(2000);
});
Since you haven't posted your HTML I can only guess what you are trying to achieve here, but based on that here's a couple of pointers:
div
elements containing your content (home, download, about, contact) probably exists only once, and should therefor have ids and not classesclick
event, make sure to use preventDefault
to stop the default event to triggerWith the above taken into consideration I've created an example that uses anchors to point to the element id in the href
attribute by using a hash, and then use that to determine which element to show.
<nav>
<a href="#home">Home</a>
<a href="#download">Download</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</nav>
<div id="container">
<div id="home">
Home
</div>
<div id="download">
Download
</div>
<div id="about">
About
</div>
<div id="contact">
Contact
</div>
</div>
$(function(){
var $menuItems = $('nav a'),
$container = $("#container");
$menuItems.on('click', function(e) {
e.preventDefault();
$(this.hash, $container).delay(300).fadeIn(1000).siblings().fadeOut(1000);
}).first().click();
});
Check out this fiddle on how the above works. Notice that I've removed the hide element since I have no idea what that is used for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With