I have an html page with a 4-item menu and 4 articles:
<nav>
<ul>
<li id="startButton"><div>Start</div></li>
<li id="servicesButton"><div>Services</div></li>
<li id="offersButton"><div>Offers</div></li>
<li id="contactButton"><div>Contact</div></li>
</ul>
</nav>
<article id="start">
<p>Start text</p>
</article>
<article id="services" hidden="true">
<p>Services text</p>
</article>
<article id="offers" hidden="true">
<p>Offers text</p>
</article>
<article id="contact" hidden="true">
<p>Contacts textº</p>
</article>
When the page is loaded only the first article is visible. With JQuery I want to change the visible article when its respective button is clicked. Also I want the li to be selectable. This is my JQuery:
$(document).ready( function (){
$('ul').selectable();
$('li#startButton').click(function() {
$('#start').show();
$('#services').hide();
$('#offers').hide();
$('#contact').hide();
});
$('li#servicesButton').click(function() {
$('#start').hide();
$('#services').show();
$('#offers').hide();
$('#contact').hide();
});
$('li#offersButton').click(function() {
$('#start').hide();
$('#services').hide();
$('#offers').show();
$('#contact').hide();
});
$('li#contactButton').click(function() {
$('#start').hide();
$('#services').hide();
$('#offers').hide();
$('#contact').show();
});
});
The problem with this script is that the hide and show part doesn't work together with the selectable part. If I eliminate the selectable line, the rest works perfectly. Does anyone know how to solve this "incompatibility" between selectable and click?
I am using JQuery 2.1.1 and JQuery UI 1.11.2
Regards, Deborah
The
hidden
attribute is not toggled by jQuery, which uses thedisplay
property of an element to show and hide. You'll need to change that using a CSS class or inline styles.Toggling sets of elements by ID is very inefficient from a code perspective. Try this instead:
Demo
You'll notice that I'm selecting articles based on the index of the list item, and that I'm chaining the
selected()
andclick()
methods.