Using JQuery to apply a CSS class or check for a CSS class on multiple button elements that

Being new to Jquery and Javascript, I am facing challenges in understanding how to implement the following.

Throughout my site, I use the same button class, and I am attempting to make Jquery apply a "clicked" class only to the button that was clicked, not to all others.

This is the code I currently have...

$(".button-img").click(function()  {
    var clickedButton = $(this);
    if (clickedButton.hasClass('clicked')) {
        return false;
    }
    clickedButton.addClass('clicked');
});

The functionality I am aiming for can be better understood in this fiddle - http://jsfiddle.net/biggee/FQqL8/1/

Despite my efforts, I still feel like I'm missing something crucial. Any assistance or guidance would be greatly appreciated.

Answer №1

Let's address a couple of issues in your code:

You had a parse error that was easily fixed by adding parentheses here:
if clickedButton.hasClass('clicked') {

Your CSS also needs correction. Instead of targeting an element with class clicked inside .button-img, you should do this:

.button-img.clicked {
    background-position:0px -60px;
}

This will target the .button-img element with the clicked class.

To simplify your code further, you can use the following snippet:

$(".button-img").on('click', function() {
    $(this).addClass('clicked');
});

Answer №2

Check out this jsFiddle Demo

Make sure to always monitor the console for any errors that may occur.

An error occurred: Uncaught SyntaxError: Unexpected identifier 

A missing parenthesis has been identified in the following code:

if clickedButton.hasClass('clicked') {

The correct syntax should be as follows:

if (clickedButton.hasClass('clicked')) {

Answer №3

Oops!

I found the solution to my own problem.

I realized that I had set up the css class incorrectly when I was trying it before.

Previously...

.button-img .clicked {background-position:0px -60px;}

Now... (and it's working)

.clicked {background-position:0px -60px;}

Thanks everyone ;)

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

Database experiencing issue with data insertion functionality

I'm facing an issue while trying to use AJAX to insert data into a database. The strange thing is that everything seems to work fine except for the actual insertion of data into the database. Upon clicking the submit button, I receive the expected mes ...

How to Create a Custom Callback Function for jQuery's .html

I am currently working with the following code: $.ajax({ type: 'GET', url: 'index.php?route=checkout/onepagecheckout/getpaypaldata', dataType: 'json', success: function(json) { ...

Suggestions for managing AngularJS within ASP.NET Web Forms?

Recently, I integrated AngularJs into a website that is built with asp.net webforms. I discovered that when using ng-Submit on a button, the form also triggers a Post call. How can I prevent the form from automatically submitting so that Angular can perf ...

Automatically fill in the Modal popup

Today, I encountered a challenge while trying to keep the current page in a jQuery data table. Clicking on the "Edit" link in a row would open a modal pop-up and fill in the controls. However, this action resulted in a postback that set the page back to pa ...

Try using Bootstrap 4 Carousel columns instead of the traditional carousel-item

Is it possible to use Bootstrap to display grid columns or rows within a Carousel instead of carousel-items? The concept involves having intricate grid column structures that rotate like carousel-items. For instance, if we have the following grid: <div ...

Tips for replacing the nested array object in JavaScript

I am seeking guidance on how to merge and overwrite the existing object values in a nested array using JavaScript. In the scenario presented below, I want to merge the 'other_obj' with the 'obj' that has an id of "zen", overwriting the ...

Creating code that adheres to the ECMAScript 5 standards

In my quest to create a JavaScript library that adheres to modern standards such as HTML5, CSS3, and ESv5, I find myself wanting to break away from the mainstream libraries like jQuery and MooTools. While these are great tools, I believe in the importance ...

Using Jquery to retrieve servlet session data

Having trouble displaying a div using servlet session attributes & JQuery. Explanation might be tricky without context. On the "result.jsp" page, there's a "Generate URL" link, an empty input text field, and an "addThis" div. When clicking on the lin ...

Validation message causing Bootstrap form inline to lose center alignment

Could someone please assist me with form inline in Bootstrap? I am trying to ensure that all inputs are of the same height (or centered), but I'm facing an issue when a validation message is displayed. DEMO: http://codepen.io/Tursky/pen/gpvgBL?editor ...

CSS: selecting the adjacent siblings of a certain class, starting from the first and

I am working on achieving the following goal: Elements containing values should have a gray 'ribbon'. Elements with values are given a class selected, while elements without any value do not have this class. This is how my HTML code appears: & ...

Enhance your product listings in Opencart 2.0 by adding supplementary images alongside the main product image

Can someone assist me with moving additional product images next to the main product image in the default opencart 2.0.1.1 theme? Currently, they are appearing below the product image and I would like them to be displayed alongside it instead. ...

When attempting to use a jQuery-formatted JSON object within an <optgroup > returned via AJAX from PHP and MySQL, it appears to be incompatible with Select2

After spending an entire day attempting to create a PHP script that converts MySQL Query results into a JSON object for <optgroup> in Select2, I finally found a solution. However, when I implemented it, nothing appeared in the Select2 dropdown menu. ...

Adjust the height of the dropdown list in react-select (React Material UI)

I recently added a dropdown feature using react-select to my project. However, I encountered an issue where the dropdown list was initially too large and taking up the entire page. I am looking for a solution on how to style the react-select dropdown list ...

I'm having trouble getting Jquery's insertAfter() function to function properly

After creating a parent div and using jQuery's insertAfter() method to insert additional divs, an unexpected issue arises. The first record goes to the bottom, while subsequent records are inserted above it. Below is the function in question: functi ...

Enhancing Dropdown Functionality Using Jquery

Hey there, I am looking to create a dropdown list/menu similar to the one shown in this image: (a screenshot). Could you please guide me on how to achieve this? Can it be done using JQUERY? Thank you in advance, Andrea ...

The div element is not resizing properly when the phone is in landscape mode

I have set a background photo to take up 100% of the height. However, when I view the site on a mobile phone in landscape mode using Chrome or Firefox, the background image does not fill the entire space. In desktop and portrait mobile modes, everything ...

IE9 does not consider JavaScript variable as undefined

Hello, I came across this JS code written by someone else: function somename(f) var procName = ""; var procParams = new Array(); var parseEl = ""; var parseEls = new Array(); var parseInd = 0; var procParamsInd = 0; var IsVal ...

Is it possible for the content of the HTML Select to vary from the options displayed in the 'drop-down' menu that the user chooses from?

When a user clicks on a dropdown menu, I want them to see the full state names in the options like this. <select name="address_region" id="address_region"> <option value=1>Alabama</option> <option value=2&g ...

Having trouble resolving this technical problem in Express.js and JavaScript programming

try { console.log('11111') const { data: { tasks }, } = await axios.get('/api/v1/tasks') console.log('22222 ' + await axios.get('/api/v1/tasks') ) console.log('33333 ' + tasks) https://i.sstatic.net/mLLV ...

"Enjoy a full-screen background that adjusts its height while you scroll

Here is how my HTML elements are nested: body { app-root { app-block-page { app-block-content { div.wrapper { *content* } } } } } body has width:100% and ...