Exchange CSS Styles with a Single Click Event in JavaScript

Struggling with getting a click event to function properly on my webpage. I have a Div labeled 'icon' with the class 'lock', and I aim to allow users to click on the background image of this Div to switch its class from 'lock' to 'locked'.

To clarify, both 'lock' and 'locked' classes are defined in an external CSS file and include background images for the Div. Additionally, I am steering clear of JQuery and instead opting for addEventListener paired with a custom function. As of now, here is a snippet of my JS code:

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 end goal can be visualized in this informative youtube video: https://www.youtube.com/watch?v=oI2sRCN7CiM

Your assistance would be highly valued as I aspire to learn and grow from any errors made.

Answer №1

One alternative approach would be to utilize the Element.classList property instead of the current method being used...

By implementing the following code snippet:

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

You can keep 'unlock' as the default class for the element. Each click on the element will toggle the presence of the 'lock' class, allowing you to customize background properties by leveraging CSS cascade with your base 'unlock' class.

Answer №2

Learn how to dynamically change CSS classes using Javascript which mentions jQuery, but you can also explore Element.className or element.classList.

To toggle between classes like 'unlock' and 'lock', consider checking the current class and then switching it accordingly. You can leverage CSS cascading properties for this purpose.

Another approach is to remove the existing class and add the new one instead:

if (elLock.classList.contains('unlock')) {
    elLock.classList.remove('unlock');
    elLock.classList.add('lock');
}
else {
    elLock.classList.remove('lock');
    elLock.classList.add('unlock');
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing my JavaScript loop to only display the final value?

Story Behind the Game In my latest project, I am delving into the world of creating a captivating 2D side-scrolling game using HTML and JavaScript. To ensure smooth gameplay, I have opted to incorporate ES6 for efficient management of all game objects. C ...

difficulties experienced in changing the z-index property in Google Chrome

When transitioning to the main_page, z-index is not behaving correctly on Chrome but works fine on Firefox. Even after setting the z-index first and then applying the transition, there is a delay in how it acts. Any assistance would be greatly appreciated. ...

Add a PHP variable to a JavaScript array

Looking for assistance with pushing a PHP variable to JavaScript. Below is the code that I have tried, but it doesn't seem to work. Can someone please guide me on how to achieve this? ticks.push(<?php echo json_encode($new); ?>); ...

Setting up an Express route with dynamic parameters in Node.js

I am in the process of creating a MEVN stack CRUD application (Vue, Node, Express, MongoDB). I'm working on setting up an Express route that will retrieve specific data from MongoDB based on the provided ID. Here is the current code snippet for the ro ...

Is sendFile causing an error due to an invalid JSON format?

Whenever I try to send a file to a client for download, I encounter an exception saying that the JSON is invalid. Is there a better way to send the file, perhaps using res.download and setting the content as JSON? I want to avoid using AngularJS FileSaver ...

Customizing App (directory) elements in next.js 13

Imagine having this directory organization: https://i.stack.imgur.com/Hd5gu.png Is there a method for loading the component from the custom folder instead of the default one in the app folder? In case the custom folder does not have that component, can t ...

Display secret content upon hovering with a stylish animation

My current structure is as follows: HTML: <ul> <li> <span>asd</span> adsafsadlvjnsd </li> </ul> CSS: span { width: 0; } li:hover span { width: 60px; } In this setup, the content inside the span tag is h ...

What is the best way to calculate the width for each of the three elements in a row so that they all have 300px

Creating my own framework using flexbox has been an interesting journey. One of the major challenges I faced with flexbox is when dealing with an odd number of elements in a row, such as 3, 5, or 7. To tackle this issue, I decided to use JavaScript/jQuery. ...

conceal a targeted section from the bottom of the iframe

I have a website embedded inside an iframe for use in a webview application. <body> <iframe id="iframe" src="http://www.medicamall.com"></iframe> </body> This is the CSS code: body { margin:0; padding:0; height:10 ...

Including a property within a nested for-loop results in identical values being assigned to every parent for-loop

I am working with an array that contains data about playing cards (cardInfo). Below is a snippet of the array in the code. Since there can be duplicates of each card, I aim to utilize this data to generate a deck by storing its information in a new array ( ...

The dropdown menu in the navigation bar is getting hidden behind the content

My simple navbar is currently functioning, but it's overlapping with other content. Both the navbar and main content elements use relative and absolute positions to function. I have tried adjusting position:absolute without success. The menu keeps ...

Is the indigo-pink color scheme fully implemented after installing @angular/material and scss using ng add command?

After running ng add @angular/material, we are prompted to choose a CSS framework and theme. I opted for indigo-pink and scss. Will the material components automatically inherit this theme, or do we need to take additional steps? When using normal CSS (wi ...

Troubles with showcasing user attributes in the view with ng-repeat and handle-bars in Angular.js

React.js, Express.js, MongoDB server.js: const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const routes = require('./routes/index'); const users = ...

The specified property 'slug' is not found within the designated type 'ParsedUrlQuery | undefined'

I am faced with an issue in my code where I am attempting to retrieve the path of my page within the getServerSideProps function. However, I have encountered a problem as the type of params is currently an object. How can I convert this object into a stri ...

What steps do I need to take to set up Vue-CLI 3 to generate a webpage with no JavaScript?

My dilemma is this: I have a simple static page that does not require JavaScript. Using vue-cli 3, I am attempting to pass the HTML file through webpack for minification purposes. Unfortunately, it seems that accomplishing this task is not as straightforwa ...

Tips for deleting the displayed URL during a web page print in PHP

Is there a way to remove the URL from a page when printing using PHP? I want to achieve this without requiring my clients to change their browser settings. Any assistance would be greatly appreciated! ...

Django: Struggling with static files and navigating paths for CSS rendering

Sorry to ask, but I'm struggling with a problem and could use some help: My project directory has the following structure (there are more directories, but for now let's focus on these): projectfolder/ wsgi/ openshift/ templates ...

The inclusion of Bootstrap 4 in the header seems to be causing issues with mouse events not functioning correctly

Exploring the functionalities of Bootstrap 4 and jQuery has been an interesting journey. I recently worked on creating a Navbar with 4 links, where the 4th link has a submenu that opens upon hover. However, I encountered an issue where this functionality o ...

What is the best way to convert an array of objects into a string in nodejs?

[ RowDataPacket { House_Name: 'Merlin 5th Avenue', no_of_rooms: 6, Cost: 3400000, PropertyId: 2 }, RowDataPacket { House_Name: 'Presidential Building', no_of_rooms: 5, Cost: 3500000, PropertyId: 106 ...

Troubleshooting the "Failed to mount component" error in Vue: fixing template or render function definition issues

Struggling with writing a Vue component, encountering the issue: Failed to mount component: template or render function not defined. Tried various fixes like adding default when importing the component, but none of them seem to work. My component code is i ...