Multiple Buttons Only Showing Button's Content
Solution 1:
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
If you have 2 you need different ID's
<divid="spoiler"style="display:none">
This is the code I use.
</div><buttontitle="Click to show/hide content"type="button"onclick="if(document.getElementById('spoiler') .style.display=='none') {document.getElementById('spoiler') .style.display=''}else{document.getElementById('spoiler') .style.display='none'}">Test</button><divid="spoiler2"style="display:none">
This is the code I use. 2
</div><buttontitle="Click to show/hide content"type="button"onclick="if(document.getElementById('spoiler2') .style.display=='none') {document.getElementById('spoiler2') .style.display=''}else{document.getElementById('spoiler2') .style.display='none'}">Test</button>
I also suggest to use a least use a function for this, example:
functiontoggleDiv(el) {
if (document.getElementById(el).style.display == 'none') {
document.getElementById(el).style.display = ''
} else {
document.getElementById(el).style.display = 'none'
}
}
<divid="spoiler"style="display:none">
This is the code I use.
</div><buttontitle="Click to show/hide content"type="button"onclick="toggleDiv('spoiler')">Test</button><divid="spoiler2"style="display:none">
This is the code I use. 2
</div><buttontitle="Click to show/hide content"type="button"onclick="toggleDiv('spoiler2')">Test</button>
For ending there are more beautiful solution specially with jQuery.
Solution 2:
In the first place, use jQuery -- it's faster to type than raw js, and immediately cross-browser.
Secondly, don't use inline javascript. It's much more difficult to read and troubleshoot. (The below script can be inserted right in amongst the html code)
Next, link your button to the elements it should operate on via IDs, as here:
<scriptsrc="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><script>
$(document).ready(function(){
$('#btnSpoiler').click(function(){
$('#spoiler').toggle();
});
});
</script><divid="spoiler"style="display:none">
This is the code I use.
</div><buttonid="btnSpoiler"title="Click to show/hide content">Show</button>
Actually, link
is probably the wrong word -- there is nothing special about the IDs per se -- I am referring to the fact that by reading the code you can easily see which button goes with which element.
However, note how the DIV was controlled via its ID.
Reasons to avoid inline javascript:
https://softwareengineering.stackexchange.com/questions/86589/why-should-i-avoid-inline-scripting
http://robertnyman.com/2008/11/20/why-inline-css-and-javascript-code-is-such-a-bad-thing/
Post a Comment for "Multiple Buttons Only Showing Button's Content"