Reputation: 57
I'm new to jQuery and I want to create my own web page. So my problem is if my menu is using href to link each item to its specified content, like this..
<li><a href="#doc1">Doc1</a></li>
<li><a href="#doc2">Doc2</a></li>
<li><a href="#doc3">Doc3</a></li>
<script>
$(document).ready(function(() {
$(a).click(function() {
$(b).show();
});
});
</script>
What should I put in 'a' and 'b'? I've tried Googling this, but all the examples didn't show the complete script. I used to do it like this:
<li id="doc1menu">Doc1</li>
<script>
$(document).ready(function() {
$("#doc1menu").click(function() {
$("#doc1content").show();
});
});
</script>
But now I want a single function that could be used for all items on my menu, instead of doing one function for each item.
Upvotes: 0
Views: 57
Reputation: 1462
try this solution(include jquery previously)
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<li><a class="menu" href="#" idmenu="doc1">Doc1</a></li>
<li><a class="menu" href="#" idmenu="doc2">Doc2</a></li>
<li><a class="menu" href="#" idmenu="doc3">Doc3</a></li>
<div class="content" id="doc1" style="display:none">doc1</div>
<div class="content" id="doc2" style="display:none">doc2</div>
<div class="content" id="doc3" style="display:none">doc3</div>
<javascript type='text/javascript'>
$(document).ready(function() {
$(".menu").click(function() {
id = $(this).attr("idmenu");
$(".content").hide();
$("#"+id).show();
});
});
</script>
Test: https://jsfiddle.net/Cuchu/cbtwndh6/
Upvotes: 1
Reputation: 1070
HTML
<li><a data-content="doc1" href="#doc1">Doc1</a></li>
<li><a data-content="doc2" href="#doc2">Doc2</a></li>
<li><a data-content="doc3" href="#doc3">Doc3</a></li>
<div id="doc1" class="content">
doc1
</div>
<div id="doc2" class="content">
doc2
</div>
<div id="doc3" class="content">
doc3
</div>
Script
$(function() {
//hide all content
$(".content").hide();
//meun function
$("a").click(function() {
var attr = $(this).attr("data-content");
$(".content").hide();
$("#" + attr).show();
});
});
https://jsfiddle.net/ynpsq1wp/1/
Upvotes: 0
Reputation: 346
Sorry my original answer was wrong due to I was trying to answer the question on my phone. try using this and whatever you would like to show/hide in replace of the 'a'. I have used the toggle method to hide/show
$(document).ready(function() {
$('li').click(function() {
$('a', this).toggle();
});
});
See js fiddle here: https://jsfiddle.net/rf5up5fr/12/
Upvotes: 0