Reputation: 2540
I'm looking for a smarter way to hide and show multiple elements. The solution I have now is to create a separate script for every element I want to show, with a click on a button.
<a class="pure-button pure-button-primary" type='button' id='hideshow1'
value='hide/show' >Show it1 !</a>
<div id='content1' style="display:none">
lorem ipsum
</div>
<a class="pure-button pure-button-primary" type='button' id='hideshow2'
value='hide/show' >Show 2 </a>
<div id='content2' style="display:none">
lorem ipsum
</div>
This is the script part:
<script>
jQuery(document).ready(function(){
jQuery('#hideshow1').on('click', function(event) {
jQuery('#content1').toggle('hide');
});
});
</script>
<script>
jQuery(document).ready(function(){
jQuery('#hideshow2').on('click', function(event) {
jQuery('#content2').toggle('hide');
});
});
</script>
This way works perfect, however I think there must be a smarter way. Anyone can give me a clue how to make it smarter?
Upvotes: 2
Views: 2090
Reputation: 116
I agree, data attributes would work really well in this situation.
$(() => {
const toggle = e => {
const content = '#content' + $(e.target).data('content');
$(content).toggle('hide');
};
$('.pure-button').on('click', toggle);
});
Upvotes: 1
Reputation: 2955
you dont have to write JS code for each element. Either you can speicify the same class class="hide"
on all a
tag and data-content=""
to toggle hide/show
(as Mostafa said). But if you want to do it by ids
. then you can follow this code.
https://jsfiddle.net/unnxnz71/
HTML
<a class="pure-button pure-button-primary" type='button' id='hideshow1' value='hide/show' data-value="content1">Show it1 !</a>
<div id='content1' style="display:none">
lorem ipsum
</div>
<a class="pure-button pure-button-primary" type='button' id='hideshow2' value='hide/show' data-value="content2">Show 2 </a>
<div id='content2' style="display:none">
lorem ipsum
</div>
JS
$('[id^="hideshow"]').on('click', function(event) {
var dataValue = $(this).attr('data-value');
dataValue = $('#'+dataValue);
$(dataValue).toggle('hide');
});
Upvotes: 2
Reputation: 3393
try this: add "data-content"
<a class="hide pure-button pure-button-primary" type='button'
value='hide/show' data-content="1">Show it1 !</a>
<div id='content1' style="display:none">
lorem ipsum
</div>
<a class="pure-button pure-button-primary" type='button'
value='hide/show' data-content="2">Show 2 </a>
<div id='content2' style="display:none">
lorem ipsum
</div>
script :
jQuery(document).ready(function(){
jQuery('.hide').on('click', function(event) {
jQuery('#content'+$(this).data("content")).toggle('hide');
});
});
Upvotes: 1