Reputation: 111
function show()
{
var elem = document.getElementById("pop").querySelector('li:nth-child(3)');
elem.style.width = "500px";
}
</script>
I have this code attached to an onclick
<li onclick="show()">
The element is originally 200px and then turns into 500px when clicked. How do I make it work so that when I click it again it goes back to 200??
Upvotes: 2
Views: 6696
Reputation: 817238
The best thing to do would be to use a CSS class to set the width. This has the advantage that:
Example:
CSS:
.wide {
width: 500px;
}
HTML:
<li onclick="show(this)">...</li>
JS:
function show(elem) {
elem.classList.toggle('wide');
}
Have a look at the MDN documentation regarding classList
for information about browser support. You can also find alternatives in this excellent question/answer about handling CSS classes on elements: Change an element's class with JavaScript
To learn more about event handling (ways to bind event handlers, information available inside event handlers, etc), have a look at the excellent articles at quirksmode.org.
Upvotes: 3
Reputation: 1349
function show() {
var elem = document.getElementById("pop").querySelector('li:nth-child(3)'),
width = parseInt(elem.style.width, 10);
if (width === 500) {
elem.style.width = "200px";
}
else {
elem.style.width = "500px";
}
}
Although, I'd probably name the function toggle
or something similar and not inline the click handler.
Upvotes: 1
Reputation: 151
Use a control variable
var clickControl = false;
function show()
{
if(clickControl)
{
var elem = document.getElementById("pop").querySelector('li:nth-child(3)');
elem.style.width = "500px";
clickControl = !clickControl;
}
else
{
var elem = document.getElementById("pop").querySelector('li:nth-child(3)');
elem.style.width = "200px";
clickControl = !clickControl;
}
}
Upvotes: 0