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??
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??
Share Improve this question edited Feb 21, 2014 at 6:43 Pranav C Balan 115k25 gold badges171 silver badges195 bronze badges asked Feb 21, 2014 at 6:35 AllTheTime1111AllTheTime1111 1113 silver badges10 bronze badges3 Answers
Reset to default 3The best thing to do would be to use a CSS class to set the width. This has the advantage that:
- You don't have to specify the width in multiple places (CSS and JS) (-> easier to maintain)
- You don't have to know the default width of the element (-> more flexible)
Example:
CSS:
.wide {
width: 500px;
}
HTML:
<li onclick="show(this)">...</li>
JS:
function show(elem) {
elem.classList.toggle('wide');
}
DEMO
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.
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.
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;
}
}