-2

I have a code for changing the class of an element onclick using pure Javascript. I was pretty confused when the code did not work as I have used the same code many times before and it worked perfectly. Here is the relevant part of the code -

HTML-

<div id="div" class="blue">.</div>

CSS-

.blue{
    width: 500px;
    height: 500px;
    z-index: 9876543210;
    position: absolute;
    margin-top: 20%;
    margin-left: 20%;
    -webkit-transition: all 0.5s ease-in-out;
    background-color: #24e;
}
.red{
    width: 300px;
    height: 300px;
    position: absolute;
    margin-top: 20%;
    margin-left: 20%;
    -webkit-transition: all 0.5s ease-in-out;
    z-index: 9876543210;
    background-color: #e69;
}

JAVASCRIPT-

function a(){
  this.classList.toggle('blue');
  this.classList.toggle('red');
}
document.querySelector('#div').addEventListener('click', a);

I have also linked the page to the online jQuery ( if that makes any difference ). When I click on the "div" nothing happens.

Please suggest a method to get past this problem.

Umesh Meena
  • 59
  • 1
  • 2
  • 4
  • 3
    Place your ` – Rayon Jun 29 '16 at 08:53
  • It worked well here though https://jsfiddle.net/z86u0p9w/ – denchu Jun 29 '16 at 08:54
  • 1
    Any javascript errors in your console when you try this? – Jamiec Jun 29 '16 at 08:55
  • you want in jquery ? – Maharajan Jun 29 '16 at 08:59
  • @Rayon That worked, I noticed that this was the only thing I had changed from the earlier times I used it. Any reason as to why it does not work when the code is written in an external js file ? – Umesh Meena Jun 29 '16 at 08:59
  • You missed out the ` – Quentin Jun 29 '16 at 09:00
  • The code is working perfectly as @denchu mentioned. Try cache refresh(Ctrl+F5) and check syntax mistakes in other parts of code. – Dani Vijay Jun 29 '16 at 09:00
  • Most likely scenario is that this question is a duplicate [of this one](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element). – Quentin Jun 29 '16 at 09:01
  • Not sure where you get "this.classlist" from, but I can say that I've had previous JQuery issues and got it fixed by placing it as far down in the code as possible, to execute it after everything else – Xariez Jun 29 '16 at 09:10
  • @Xariez — https://developer.mozilla.org/en-US/docs/Web/API/Element/classList – Quentin Jun 29 '16 at 09:45
  • Ah, thank you! Haven't seen that before but good to know where he got it from! @Quentin – Xariez Jun 29 '16 at 11:46

1 Answers1

-1

If you have jquery included , you can use .click() function to capture the click event of div. To toggle between class, use toggleClass. blue is the first class added and hence , red will be toggled with the div

$('#div').click(function(){
       $('#div').toggleClass("blue red");
})
Manikandan
  • 1,188
  • 10
  • 18