Switch the class of a div using jQuery when it is clicked

I need to implement functionality where 4 different links change the class of a specific div when clicked. For example, clicking on link 1 will change the class to s1, link 2 to s2, and so on.

Below is some code that I have been working on, however, I am still learning jQuery and not sure about the implementation:

http://jsfiddle.net/Nh7tn/1/

<div class="vehicleJourney">
    <div id="progress">
        <div id="complete" class="s2"><!--need class to change -->
            <div id="marker"></div>
        </div>
    </div>

    <div class="buttons">
      <ul>
        <li class="s1"><a  class="showSingle" data-target="1">s1</a></li>
        <li class="s2"><a  class="showSingle selected" data-target="2">s2</a></li>
        <li class="s3"><a  class="showSingle" data-target="3">s3</a></li>
        <li class="s4"><a  class="showSingle" data-target="4">s4</a></li>
      </ul>
    </div>

</div>​

Any help or suggestions would be greatly appreciated. Thank you!

Answer №1

To apply a class from the text of a link to a div, you can use the following code:

$('a.showSingle').click(function(){
   $('#complete').attr('class', $(this).text()); 
});

See Demo

If you want to assign the class of the parent of the link to the div, you can do this:

$('a.showSingle').click(function(){
   $('#complete').attr('class', $(this).parent().attr('class')); 
});

See Demo

If you wish to set a class on the div based on the number of the link, you can use this code:

$('a.showSingle').click(function(){
   $('#complete').attr('class', 's'+($(this).parent().index()+1)); 
});

See Demo

When implementing this in your actual application (outside of jsfiddle), make sure to include the script inside a ready callback at the end of your body:

<script>
    $(function(){
       $('a.showSingle').click(function(){
          $('#complete').attr('class', 's'+($(this).parent().index()+1)); 
       });
    });
</script>

Answer №2

Give this a shot:

$(document).ready(function() {
    $('.showSingle').on('click', function() {
        $('#complete').removeClass().addClass('s' + $(this).data('target'));
    });
});

Answer №3

Check out the latest version on jsfiddle

$('.showSingle').click(function(){$('#complete').attr('class',$(this).html());});

Answer №4

It should do the trick

$("li a").on('click', function(){
  let className = $(this).text();
  $("#complete").attr("class", className);
});

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

From dividing into three sections to splitting into two sections

Struggling to create a list of images and descriptions in sets of threes at larger widths, transitioning to twos at smaller widths? The breakdown is causing chaos. Need help achieving clean one-half columns. Appreciate any assistance! ...

Ways to dynamically insert a new row into a table based on user input in a Postman-like reactive table

Is there a way to dynamically insert a row when a single character is entered into an input field in the header tab, similar to how Postman functions? 1) If a user types any single character in the td of the first row, then a new row should be added below ...

Ways to constrain checkbox choices to only one within an HTML file as the checklist with the checkboxes is being created by JavaScript

I am working on developing an HTML dialogue box to serve as a settings page for my program. Within this settings page, users can create a list of salespeople that can be later selected from a drop-down menu. My current objective is to incorporate a checkbo ...

The data-ls attribute is currently not permitted on the svg element. Is there a way to fix this issue?

Upon running my site through the w3cvalidator tool, I encountered the following errors: "Attribute data-ls not allowed on svg element at this point" and "End tag svg did not match the name of the current open element (use)". Below is a snippet of the cod ...

Attempting to repair navigation menu on grou.ps website

Hey there, I'm currently working on improving the appearance of my website. The original site can be found at . After integrating it with the grou.ps community platform, I noticed that the navigation menu is not displaying correctly and the image is ...

Exploring the intricacies of React Router parameters

I have been facing some issues with my routing setup. Specifically, I have a static route called list and a dynamic route called user/:id. The problem arises when navigating between these two pages. (1) Whenever I navigate to the list route from the user/: ...

Utilizing JavaScript in Protractor, explore a list to identify the selected checkboxes and those that remain unchecked

Currently, I am working on developing an end-to-end test using Protractor. My main objective is to extract the names from a list and then determine which checkboxes have been selected and which ones haven't. To check the state of the checkbox, I pla ...

The content is stationary as the side menu slides open and closed

I have successfully implemented a sliding side menu in my angularjs+bootstrap3 app using CSS. However, I am facing an issue where the content on the right side does not follow the menu when it slides out of view. Here is the desired effect that I am aimin ...

Discover the best way to showcase items within an arrayList using dual CSS styles!

I'm currently working on a project that involves an arrayList with two names: Bob and Steve. I have the requirement to display them in different colors, where Bob should be displayed in green and Steve in red. Component.CSS .Bob{ font-weight:bold; ...

Unveiling the Mystery: Java Tips for Capturing the Chosen Value from a DropdownChoice in Apache W

In my Java class, I created a method where I instantiate a DropDownChoice object for a select menu and add it to the form. Within this method, I am populating the projects list into the billableProjectsList. public class ReportCriteria implements Serializa ...

jQuery AJAX Live Search Function Only Executes Once

Here is a code snippet for a live search functionality: <script> $(".search").keyup(function() { var Team_Name = $('#TeamName').val(); var Teacher = $('#Teacher').val(); var Searc ...

Disable the ability to select text when double-clicking

Is there a way to prevent text selection on double click while still allowing selection on mouse drag? Whenever I try to remove selection on dblclick or mouseup, it flashes, which is not the desired outcome as shown in this jsfiddle. UPD: I am not lookin ...

How can I alter the image using the success function in jQuery?

I'm encountering an issue with my jQuery voting script. Everything seems to be working correctly, except for the fact that the image in the success function of the AJAX request is not updating as expected. jQuery: $("a.vote_down").click(function(){ ...

Ways to determine if the backbone.js model has been emptied

I often find myself wondering how to determine if a model has been cleared or is empty. For example, if I set the model with: model.set({name:'this is a test', id:1}); and then clear it with: model.clear(); ...

Navigating a Multi-Page Website with Sleek Scrolling

I've been searching for a solution everywhere but haven't had any luck. I'm trying to implement a smooth scroll effect that works seamlessly across multiple pages. For instance, the smooth scroll effect is present on the homepage with naviga ...

I attempted to log the elements of my submit button form, but unfortunately nothing is appearing in the browser console

I am attempting to capture the data from my submit button form, but for some reason, nothing is showing up in the console of my browser. $("#signupform").submit(function(event){ // Stopped default PHP processing event.preve ...

What is the best way to add an image to a SVG placeholder?

This is all unfamiliar territory for me. I am experimenting with the Bootstrap template named "Carousel" as my starting point, utilizing Bootstrap 5.3.2. Here is the link to the Carousel example Everything seems fine so far. However, I am struggling to l ...

JWPlayer has a built-in delay of 5 seconds before executing an action following the completion of a

I am looking to customize the JWPlayer so that it pauses for 5 seconds before playing the next video. Additionally, I want to display a loading animation at the center of the video similar to what is seen on YouTube. Here is the code snippet I am currently ...

Fade away a division with content C, and Fade In the identical division with content D

Here is the script I currently have: $(function() { $('.ajaxloader').click(function(event) { var target = $(this).attr('href'); window.location.hash = target; $('#conteudoInscricao').fadeOut( ...

Is there a way to collapse child elements in a hover sidebar using Vuetify?

My project includes a sidebar that opens when I hover over it with the mouse. Everything works fine, but within the sidebar, there is a collapse dropdown menu. When I open this menu and then move the mouse away from the sidebar and back again, the collapse ...