Imran Omer
Imran Omer

Reputation: 701

Change Link BG Color onClick

I want to change the BG color of a link when the user clicks on it/onClick. Here is the code I am currently working on;

<a href="javascript:void(0);" onclick="myFunction()" class="dropbtn" id="dropbtn">Link Drop Down</a>
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
  document.getElementById("dropbtn").onclick = function()
    {
        this.style.background = '#FFF';
    }
}

But it didn't worked and I am not sure why.

Upvotes: 0

Views: 74

Answers (2)

Niloct
Niloct

Reputation: 9995

<a href="javascript:void(0);" class="dropbtn" id="dropbtn">Link Drop Down</a>

function myFunction() {
  document.getElementById("dropbtn").onclick = function(event) {
    var drop_down = document.getElementById("myDropdown");
    if (!drop_down.classList.contains('show')) {
        drop_down.classList.add('show');
        this.style.background = '#FFF';
    }
    else {
        drop_down.classList.remove('show');
        this.style.background = '';
    }
    return true; 
  }
}
myFunction(); 

Basically you have to install the onclick Event handler (see https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers) , which receives an event parameter with event info. this inside it actually points to the element with id=dropbtn, so you can either reference it directly as in your question or get the reference that is on event.target.

EDIT

Actually I was wrong, sorry, this indeed points to the element clicked. Fixed the answer.

Upvotes: 1

Akash Bhardwaj
Akash Bhardwaj

Reputation: 356

Try this:

<a href="javascript:void(0);" onclick="myFunction(e)" class="dropbtn" id="dropbtn">Link Drop Down</a>


function myFunction(e) {
  document.getElementById("myDropdown").classList.toggle("show");
  e.target.style.background = '#FFF';
}

Upvotes: 0

Related Questions