0

I have this anchor which has an onclick function that changes the background color of certain div to green. It is properly working but the problem is it needs to be double clicked in order for the function to be executed.

HTML:

<a onclick="btngreen()" href="">MENU</a>

Javascript:

function btngreen(){
    document.getElementById("nameofdiv").style.backgroundColor = 'green';
}
Majid Parvin
  • 4,499
  • 5
  • 29
  • 47

4 Answers4

0

You could use ondblclick

<a ondblclick="btngreen()" href="">MENU</a>
rbock
  • 625
  • 5
  • 15
  • 2
    I think his problem is that right now he has to double click even though it has a onclick handler. – James May 24 '17 at 16:44
0

As per my understanding of your problem.

Try this code. use # in href

<a onclick="btngreen()" href="#">MENU</a>

or you can use

<a onclick="btngreen()" href="javascript: void(0)">MENU</a>
Dinesh undefined
  • 5,490
  • 2
  • 19
  • 40
0

Works fine for me. Only issue I had was your empty href="" tag so I removed it. You could also use href="#" if you do not want to remove it.

<script>
  function btngreen(){
    document.getElementById("nameofdiv").style.backgroundColor = "green";
  }
</script>

<a onclick="btngreen()" href="#">MENU</a>

<div id="nameofdiv" style="width:100px;height:100px;"></div>
Ken
  • 466
  • 2
  • 7
0

If you do not need the button to be a link, you could simple change it to another tag such as <p> since the a will be trying to naviagte the page.

<p onclick="btngreen()">menu</p>
<script type="text/javascript">
    function btngreen(){
        document.getElementById("nameofdiv").style.backgroundColor = "green";
    }
</script>

or you could also just default the link to not navigate from the page such as this example below.

<a onclick="btngreen()" href="#">menu</a>
<script type="text/javascript">
    function btngreen(){
        document.getElementById("nameofdiv").style.backgroundColor = "green";
    }
</script>

Using the href="#" is a dead link and will not navigate the page anywhere.

jkeys
  • 431
  • 3
  • 10