1

I am having trouble getting a click event to work on a page. I have a Div with an ID of 'icon', and the class of 'lock', and I want to be able to click on this Div's background image to change the class from 'lock' to 'locked'.

Before any confusion happens, I have both classes in my external CSS file, and they add a background image to the Div. Also, I don't want to use JQuery, but addEventListener with a function. so far, this is what my JS looks like:

var elLock = document.getElementById('icon');
function changeLock(){
    var imgSwitch = elLock.getAttribute('class');
    if(imgSwitch !== 'unlock'){
        elLock.className = 'unlock';

    }else{
        elLock.className('lock');
    }
}

elLock.addEventListener('click', changeLock, false);

The desired result is what is in this youtube video: https://www.youtube.com/watch?v=oI2sRCN7CiM

Any help would be greatly appreciated. I would love to learn from mistakes i've made.

Stiel
  • 13
  • 2

2 Answers2

0

I would use the Element.classList property rather than what you're doing here ...

Then you could simply do:

elLock.addEventListener('click', function() {
    elLock.classList.toggle('lock') },
    false);

and leave unlock as a default class on the element. Every time you click on the element, it will toggle the lock class on-and-off, and you can use the cascading properties of CSS to override the background properties that are on your default unlock class.

Jason
  • 31,834
  • 7
  • 59
  • 78
  • Thank you for your response! I will first have to learn how to use the Element.classList property. I will let you know how it works for me after I try it out. – Stiel Mar 21 '15 at 04:34
0

Change an element's CSS with Javascript may provide some help, although it does reference to jQuery. Element.className could be what you need, or element.classList.

I'd check if the current class is 'unlock'. If one class is considered a default, the other class can toggle. Using CSS's cascading properties will allow the toggling class to override the default when it is present.

Alternatively you could remove the currently applied class and apply the other.

if (elLock.classList.contains('unlock')) {
    elLock.classList.remove('unlock');
    elLock.classList.add('lock');
}
else {
    elLock.classList.remove('lock');
    elLock.classList.add('unlock');
}
Community
  • 1
  • 1
ninjabugs
  • 103
  • 7
  • Thank you for responding, I did look at the first link earlier today, but I do not want to use JQuery. I will look through the other links you provided, as they seem promising. It will take some studying, because I don't know how to use either (I'm a complete beginner.) – Stiel Mar 21 '15 at 04:32