Open/close a list w/out jquery

I have a list, and am trying to open/close it with a link (onclick) but want to start from scratch, heres the HTML


<a href="">Click here to view full list</a><ul><li>Test 1</li><li>Test 2</li><li>Test 3</li><li>Test 4</li><li>Test 5</li><li>Test 6</li></ul><p>This is the next line of text</p>

Im trying to make it so that when I click the linmk, the list, will toggle and the (plus) image next to it will change (screenshoit)

Thanks…

Here goes:


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Demo Toggle Display</title>
<script>
function toggleDisplay(listId,caller) {
    var theList = document.getElementById(listId);
    if (theList.style.display == 'none') {
        theList.style.display = 'block';
        caller.style.backgroundImage = 'minus-sign.gif';
    }
    else {
        theList.style.display = 'none';
        caller.style.backgroundImage = 'plus-sign.gif';
    }
}
</script>
</head>
<body>
    <a href="#" onclick="toggleDisplay('firstList',this); return false">Click here to view full list</a>
    <ul id="firstList" style="display:none">
        <li>Test 1</li>
        <li>Test 2</li>
        <li>Test 3</li>
        <li>Test 4</li>
    </ul>
    <p>This is the next line of text</p>
</body>
</html>

In contrast to normal practice, I would advise to set the initial display of the list inline. This is because javascript only reads inline CSS, not CSS blocks in the head or of separate style sheets.

Good thing that you’re trying to learn native javascript. As you can see, it doesn’t have to be difficult.

thanks frank. Am trying to go through your code and am a little lost, can you explain the javascript?

like, im having trouble figuring out how to display the background image

Hey,

I made a mistake in the backgroundImage part. This is what it should have read:


<script>
function toggleDisplay(listId,caller) {
    var theList = document.getElementById(listId);
    if (theList.style.display == 'none') {
        theList.style.display = 'block';
        caller.style.backgroundImage = 'url(images/minus-sign.gif)';
    }
    else {
        theList.style.display = 'none';
        caller.style.backgroundImage = 'url(images/plus-sign.gif)';
    }
}
</script>

I presume that you have your images in a folder called ‘images’. Displaying can be done like this:


<style>
a {
   padding-left: 20px;
   background-image: url(images/plus-sign.gif);
   background-repeat: no-repeat;
}
</style>

thanks, what does caller.style.backgroundImage do?

It assigns the background designated in the function to the parameter passed to it.