Question

I want a Pure JavaScript code that will change an image and also its link to another image and another link on same place as toggle function. I have a web page and I have Anchors Links button as <a href="#DIV2"><img src="DownArrow.png"/></a> and I want that after clicking on this image, first it will lead you to the DIV2 and then it will change the code to <a href="#DIV1"><img src="UpArrow.png"/></a>. How to do this using pure JavaScript? Waiting for perfect reply and code?

Was it helpful?

Solution

This should work:

var link = document.querySelector('#arrow a');
link.onclick = function() {
    var image = document.querySelector('#arrow a img');
    if(this.href.slice(-1) === '1') {
        this.href = '#DIV2';
        image.src = 'https://cdn1.iconfinder.com/data/icons/nuvola2/48x48/actions/1uparrow.png';
    } else {
        this.href = '#DIV1';
        image.src = 'https://cdn1.iconfinder.com/data/icons/nuvola2/48x48/actions/1downarrow.png';
    }
}

See it in action here: http://jsfiddle.net/TM9ap/7/

Note that I've changed the href attribute in the link to #DIV1 like this <a href="#DIV1">

OTHER TIPS

<!DOCTYPE html>

<html>
<title></title>
<head></head>
<body>
<a href = "#DIV1" style="color:BLACK;" onclick="execute();">Click me 
    <img src="UpArrow.png" />
</a>
<div id="DIV1" ></div>

<div id="DIV2" ></div>  
<script>


function execute()
{

if ( document.getElementsByTagName("a")[0].getAttribute("href")==="#DIV1"){
    var img = document.getElementsByTagName("img")[0];
    img.setAttribute("src","DownArrow.png");
    img.parentNode.setAttribute("href","#DIV2");
}
else 
{


    var img = document.getElementsByTagName("img")[0];
    img.setAttribute("src","UpArrow.png");
        img.parentNode.setAttribute("href","#DIV1");
}

}




</script> 

</body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top