I have a div that I want to toggle between displaying or not when a user clicks on a piece of text. I have a javascript function that toggles a div on or off. That works fine. What I don't know how to do is to have a triangle that points to the right or down depending on whether the div is open.
My HTML looks like this:
<a onclick="toggleDiv('myDiv');">Click here to expand or close div</a>
<div id="myDiv" style="display:none">
...
</div>
How do I add one of those triangles and have it point the right way, ideally with just HTML, Javascript, and CSS? The triangle would appear to the left of the "Click here..." string.
Thanks.
Your toggleDiv()
function would be helpful to see here. Anyhow you should probably just add a class to your div
, perhaps "active" or "open".
Then in your CSS, do something like:
div {
background: url("downarrow.png") top left no-repeat;
}
div.open {
background: url("uparrow.png") top left no-repeat;
}
update
You also may consider moving your JS out of your HTML entirely, you can observer the click event on the element from your JS, then add the class or remove it based on it's state. Maybe consider using a library like jQuery.
There are a number of options. First you will need the two images, let us call them uptri.jpg and downtri.jpg. Then you can create two CSS classes:
.up{
background-image:url(../images/uptri.jpg);
background-repeat:no-repeat;
}
.down{
background-image:url(../images/downtri.jpg);
background-repeat:no-repeat;
}
Then with some JavScript you can swap out the up class for the down class. I would suggest using jQuery since it makes it trivially easy.
$("#myClicker").toggle(
function(){$(this).removeClass('up');
$(this).addClass('down');
},
function(){$(this).removeClass('down');
$(this).addClass('up');
}
);
Where myClicker is the id of your link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With