Reputation: 47
For a simple toggle based on classes in buttons and p tags, do I have to repeat the script each time? I'm new to JS and trying to learn this. Example of code below!
https://jsfiddle.net/14u4bs6x/
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".but1").click(function(){
$(".type1").toggle();
});
});
</script>
<script>
$(document).ready(function(){
$(".but2").click(function(){
$(".type2").toggle();
});
});
</script>
</head>
<body>
<button class="but1">button1</button>
<button class="but2">button2</button>
<p class="type1">#1</p>
<p class="type2">#2</p>
</body>
</html>
Upvotes: 1
Views: 89
Reputation: 1248
Simple example:
function toggle(id){
$(".type_"+id).toggle();
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<button onclick="toggle('1')">button1</button>
<button onclick="toggle('2')">button2</button>
<p class="type_1">#1</p>
<p class="type_2">#2</p>
</body>
</html>
Upvotes: 0
Reputation: 337560
If you follow DRY principles then you can solve this by using a common class on the button
elements to attach your event handler, and setting a data*
attribute on each one individually to specify the element that should be toggled, like this:
$(document).ready(function() {
$(".but").click(function() {
$("." + $(this).data('target')).toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="but" data-target="type1">button1</button>
<button class="but" data-target="type2">button2</button>
<p class="type1">#1</p>
<p class="type2">#2</p>
Alternatively you could set the relationship by their indexes. This means you don't have to change the HTML but is a little more fragile and easily broken.
$(document).ready(function() {
$('.but').click(function() {
$('.type').eq($(this).index('.but')).toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="but">button1</button>
<button class="but">button2</button>
<p class="type">#1</p>
<p class="type">#2</p>
Upvotes: 2