Is it possible to manipulate class attributes using an if statement in your code?

I am looking to dynamically change the classes based on user clicks on two different headings.

When heading one is clicked, I want the font color to turn red and be underlined in red as well. The styling changes are already set up in the respective classes. If heading two is clicked, then it should adopt these red styling characteristics. The unclicked heading will remain grey according to the "no_highlight" class.

To see an example of what I'm trying to achieve, please refer to this JSFiddle: http://jsfiddle.net/7ok991am/1/

HTML:

<div id="page_headings">
    <h2 class="no_highlight">Heading One</h2>
    <h2 class="no_highlight">Heading Two</h2>
</div>

CSS:

#page_headings{
    overflow: hidden;
    margin-bottom: 32px;
}

#page_headings h2{
    float: left;
    margin-right:24px;
    font-size: 14px;
    cursor:pointer;
}

#page_headings h2:hover{
    font-weight: bold;
}

.red_highlight{
    color:red;
    border-bottom: 1px solid red;
}

.no_highlight{
    color:#898989;
}

JS:

$('#page_headings').on('click', function(){
    if($('#page_headings h2').hasClass('no_highlight')){
        $(this).removeClass('no_highlight').addClass('red_highlight');
    }else{
        $('#page_headings h2').addClass('no_highlight');
    };
});  

Answer №1

Expanding on @RDrazard's answer, I believe the goal is to enable users to toggle between both options, correct?

http://jsfiddle.net/abc123de/5/

$('#page_titles h2').on('click', function(){
if($(this).hasClass('no_highlighted')){
    $(this).removeClass('no_highlighted').addClass('blue_highlighted');
}else{
    $(this).addClass('no_highlighted');
}
$(this).siblings('h2').addClass('no_highlighted');
});  

Answer №2

Here is a JSFiddle link: Click Here

To start, make sure to include a border-bottom property with the value of none in the no highlight class to maintain its appearance before being clicked.

Then, you should target the click event for h2 elements by using $('#page_headings h2')

Remember to utilize this to affect the specific h2 element that is being clicked on.

Answer №3

Check out this sample code:

$('#page_headings h2').on('click', function(){
  if($(this).hasClass('no_highlight')){
    $(this).removeClass('no_highlight').addClass('red_highlight');
  }else{
    $(this).addClass('no_highlight').removeClass('red_highlight');
  }
});

Answer №4

Take a look at this code snippet

JavaScript

$('.no_highlight').on('click', function(){
    $(this).parent().find('.no_highlight').css('border-bottom','none');

    $(this).css('border-bottom','1px solid red');
});  

The above code snippet changes the border of the currently clicked heading, which could be what you're looking for.

Also,

If you prefer using addClass() and removeClass(), then check out this example

JavaScript

$('.no_highlight').on('click', function(){
    $(this).parent().find('.no_highlight').removeClass('red_highlight');

$(this).addClass('red_highlight');
});

This specific approach adds a 'red_highlight' class to the active link and removes it when not in use.

Please give it a try!

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

How can I simply show a specific value from an object in Vue?

I've created a Vue application that filters messages and displays them on a page. Currently, when a user selects a message from the list, the entire JSON data associated with that message is shown on the page. However, I want to only display a specifi ...

Refining a JQuery scroll animation using mouseover functionality

I came across a JQuery scroll animation (inspired by this specific answer to a similar question that almost perfectly suited my requirements), and I managed to get it working. My goal is to achieve a side-scroll effect of icons when the user hovers over th ...

Rotating Social Media Symbols - bootstrap 4

I am looking to incorporate a Social Button Footer similar to the one in this CodePen example: (https://codepen.io/vpdemo/pen/WbMNJv). However, my buttons are not appearing as circles. How can I rectify this? a, a:hover { text-decoration: none; } .soc ...

Is there a way to verify Page.Validate() using client-side JavaScript in ASP.Net?

Is there a client-side function in JavaScript that can perform page validation similar to the server-side method Page.Validate()? ...

Prevent the print dialog window from appearing when a page loads in Selenium for Firefox and Chrome

Is there a way to prevent the print window from automatically popping up when a page loads using Selenium? So far, I have tried using the Robot class to press the escape key, but it only works 80% of the time. I have also experimented with Firefox prefere ...

What is the best way to show <input type='text'> without generating a textbox using jQuery?

When a user enters a comment in the text box and hits enter, it is automatically displayed in the 'comment section'. Upon hitting submit, the following code is executed: var comment = $("#commentBox").val(); var commentSection = $("#commentSecti ...

"Encountering an issue with supabase.auth.getUser() when implementing a vue-router route guard

My Vue application project involves integrating Supabase authentication. In one of the route guards within the router file, I used supabase.auth.getUser() to determine the user's login status and control the execution flow based on that condition: // ...

Streamline the process of sorting through 2 arrays

Is there a more concise and elegant way to achieve the same functionality as my current method? I am looking for a shorter solution to create an array of items that haven't been used in the form previously, which are then used to populate a select dro ...

Express server failing to serve js and css files

Currently, I'm working on a ReactJS project with React Router implemented. When attempting to access /dashboard/stream, the server is returning the index.html file successfully. However, there are 301 errors for the CSS and JS files, resulting in noth ...

Having trouble with vscode [ctrl+click] on 'vue single-file components' and 'go to definition'? It's not working for me

// src/ui/tabbar/Index.vue <template> <div> my-tabbar component here </div> </template> // src/ui/index.js import MyTabbar from './tabbar/Index.vue' export default { install(Vue) { Vue.component(MyTabbar.na ...

What could be the reason that a MUI component does not disappear when the display is set to none in the sx prop?

I'm attempting to construct a responsive side drawer using MUI's Drawer component in React, specifically leveraging MUI version 4.12.1. In the example provided on the mui.com website, they utilize the sx prop and pass an object with different di ...

Using JQuery, identify cells located in the first column of a table excluding those in the header section

In the past, I had code that looked like this: $(elem).parents('li').find(...) I used this code when elem was an item in a list, making it easy to reference all items in the list. But now, I've made some changes and decided to use a table ...

jquery asynchronous image loading technique

Can images be loaded asynchronously while the page is loading? The images will only be displayed when a user clicks on a button, rather than immediately showing up. As a result, I am curious if it's feasible to preload the images in a cache so that th ...

@keyframes shimmering-fade

I'm attempting to create a text animation effect (please see video) but I'm struggling to find the solution!! Can someone assist me with this? Should I use JavaScript for a better result? h1.fadeinone { animation: fadeinone 10s;} h1.fadeintwo ...

How to Use jQuery to Iterate Through a JSON Array and Add to an HTML Container Element?

I'm currently embarking on a personal project and have a query relating to jQuery and its usage in looping through a JSON array. Here is the JSON array I am working with: var thumbDir = [ '"https://www.location.com/1.jpg"', '"https:// ...

Notify of a specific value in an array that is retrieved through an AJAX request

I'm currently facing an issue with trying to display the value obtained from an ajax call. The code snippet below is functional in such a way that it will successfully alert the value of 'row' when grid.onClick is triggered. However, I am st ...

What is the process for altering a variable within an Ajax function?

Scenario: I'm dealing with JSON data fetched from the backend which needs to be presented in a table format. To achieve this, I've created a string called tableOutputString and am populating it by iterating through the JSON response. Finally, I&a ...

jQuery fails to retain multiple classes when appending elements

Strange things are happening when I use jQuery. I create a string like this: myBlock = """<div class="alert alert-success">...</div>""" But when I try to append it using jQuery, $("#msg_container").append(myBlock) The resulting div in the ...

issue with mobile toggle functionality in bootstrap 4

I have successfully implemented a mobile nav using Bootstrap 3, but now I am trying to upgrade to Bootstrap 4. I am testing with local versions of the files and I believe everything is set up correctly. However, the toggle on mobile is ...

Managing variables or properties that are not defined in ES6

Currently, I am utilizing Angular and Firebase Firestore in my project. However, the question posed could be relevant to Typescript and pure Javascript as well. The functionality of my application relies heavily on the data retrieved from Firestore. A sim ...