Toggle the jQuery class off when a different element is chosen

I've created a function that toggles a class to change the style of an element when it is selected. However, I'm facing an issue where the new style remains even when another element is selected. Is there a way to make the styling revert back to the original when a new element is selected using this existing function?

<script>
    $('.stylingchange').click(function() {
        $(this).toggleClass('servicesiconchange');
    });
</script>

Answer №1

To modify the styling of certain elements, remove the specific class from each element and then toggle the class on the current element.

$('.stylingchange').click(function() {
             $('.stylingchange').removeClass('servicesiconchange');
            $(this).toggleClass('servicesiconchange');
        });

Take a look at this example I created on JSFIDDLE

Answer №2

To remove a specific class from all instances, you can utilize the removeClass() method and then toggle the class on the clicked element.

$('.changeStyle').on('click', function(){
    $('.iconChange').removeClass('iconChange');
    $(this).toggleClass('iconChange');
});

If you want to narrow it down to a particular class, you can achieve that with the following code:

$('.changeStyle').on('click', function(){
    $('.changeStyle.iconChange').removeClass('iconChange');
    $(this).toggleClass('iconChange');
});

Answer №3

$('.stylingchange').on('click', function(){
  $('.stylingchange.servicesiconchange').not(this).removeClass('servicesiconchange');
  $(this).toggleClass('servicesiconchange');
})

Start by finding any elements with the styling change class that are not the current item, remove the styling change class from them, and then toggle the styling change class on the current item.

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

Is there a way to create a fixed container aligned to the right and have the parent container handle scrolling?

My setup is as follows: Full width, 100px height header The header is always visible at the top. Full width, remaining height details The content of details can scroll vertically and horizontally. A fixed 200px width, full height container is right- ...

Transfer information from the ajax success event to an external else/if statement

I am encountering an issue when trying to transfer the appropriate result from my ajax success function to an external function for further use. Currently, I am using user input to query a data source via ajax and receiving the object successfully. The re ...

Generate HTML tags dynamically within a JSON document using PHP

Is there a way to incorporate HTML markups (generated dynamically by a CMS) into a JSON file? I am aware that in the html string, one must escape double quotes by adding "" as shown below. { "title": "Title", "da ...

showing errors in case the username does not match the specified pattern

As I work with symfony, one of the challenges is displaying errors when the username does not fit the specified pattern. How can this be achieved? {{ form_widget(form.username, {'attr':{'pattern': '[a-zA-Z]*'} }) }} ...

What is the best way to align text in the middle on smaller devices like phones and iPads?

I have been working on a login screen and encountered a problem with the layout on smaller devices. Despite centering all the content perfectly on my computer's browser, when I inspect it using developer tools for smaller devices, everything shifts to ...

The drop-down menu seems to have disappeared from sight

I'm having an issue with getting a dropdown to appear in my registration form. Everything else in the form is displaying correctly and functioning properly, but the dropdown remains invisible. After searching extensively, I haven't been able to ...

Shifted picture next to the accompanying words

I have successfully created a slideshow of images using JavaScript. <html> <head> <script language="JavaScript"> var i = 0; var path = new Array(); path[0] = "one.jpg"; path[1] = "two.jpg"; function swapImage() { document.slide ...

No departure animation employed - Polymer

I am working on a project that involves animating a paper-icon-button with spin and opacity effects when hovering over an image using the on-mouseenter and on-mouseleave events. Everything works smoothly when hovering over the image, but I am facing an is ...

Generate a progress indicator upon user clicking a hyperlink

I am looking to implement a loading bar that appears when the user clicks a link. Additionally, I need to upload data (via Ajax) into div#work if needed, followed by displaying the loading bar. Once the data is successfully uploaded, I want the script to s ...

Effortlessly glide to a specific element on an HTML page

I am working with XML data that contains a lot of Test information. I am using XSLT to display this data as HTML in a web browser. Each test includes a table with the test steps, and every time a test is executed, the table updates to show whether each s ...

Easily transferring the entire form using jQuery

Here's the code I'm working with: http://jsfiddle.net/aH2qC/ I am currently facing an issue where the code is not functioning as expected. What I need to do is extract the content from the form's action="" attribute and utilize it as the u ...

Utilizing jQuery to Detect TAB Key Press in Textbox

I need to detect when the TAB key is pressed, prevent the default action from occurring, and then execute my custom JavaScript function. ...

List of shapes and text items

I'm encountering some challenges with my list of shapes - could it be that I am approaching it the wrong way? I could use some guidance on what I am trying to accomplish. Check out My Fiddle CSS: #circle { height: 120px; width: 120px; b ...

Retrieving server information using AJAX in React

I've been attempting to utilize an AJAX call in order to fetch server data for my React Components. However, I'm encountering difficulties when it comes to displaying it with React as I keep receiving this error: Uncaught TypeError: Cannot read ...

Show the Div container when one of the checkboxes is selected

Currently, I have implemented a show/hide functionality for a div element when a checkbox is clicked. The div appears and remains visible until all checkboxes are checked; however, if no checkbox is checked, the div disappears. The issue I am encountering ...

Storing a string in an array in PHP: A step-by-step guide

I'm facing an issue with storing a string in an array, as it seems to not save the changes in the array properly: <?php session_start(); $username = $_POST["username"]; $password = $_POST["password"]; $users = array(); $passe ...

Setting a uniform width for all columns in a table using ReactJS

When working with variable amounts of data displayed as columns in a table, I struggled to maintain fixed widths for each column. Despite my efforts, the columns would stretch based on available space rather than obeying the specified widths. For example, ...

The element 'Listitem' is unrecognized and cannot be found in the current context

I am currently working on an ASPX project in Visual Studio and have encountered an issue with a Drop Down field. It appears that the List Items are being ignored in my code. Can anyone advise me on what might be missing? <form runat="server"> &l ...

Trigger click functions sequentially to display elements after specific actions are taken

Is there a way to make jQuery listen for clicks only at specific times? It seems that when I add event listeners, like $("#box").click(function(){, they are executing before the code above them finishes running. Let's say I have two boxes that should ...

Transfer a file from the file:///var/mobile/Applications/ directory to an accessible location for reading in Cordova/PhoneGap

I have a unique 'whitelabel' app that customizes itself for each client by downloading image files from a configuration server. However, I am facing an issue where the images are not displayed and instead showing a "Not allowed to load local reso ...