Changing the CSS class dynamically by clicking with jQuery

I'm in the process of setting up a WordPress website, utilizing this specific template obtained from ThemeForest. You can view the live preview here of what I am currently working on (which should be functioning properly now - kindly inform me if it's not).

The CSS has been configured so that when hovered over, the left border turns light gray. Subsequently, upon clicking the link, the left border changes to the blue color selected.

My main issue with the navigation lies within the CSS as depicted below. The Portfolio link (Portfolio Section in the picture) still retains the selected class along with the inner unordered list item. My goal is for it to resemble the Blog Section in the image, where the Blog link no longer displays the selected class.

Upon consulting the template creator regarding this dilemma, I was informed that an additional link with the title attribute 'allportfolio' needed to be added beneath for proper functionality. I attempted adding this attribute to the primary Portfolio link but ended up closing the list entirely.

When the menu is generated, the browser structures the Portfolio selection in HTML like so:

<ul class="main-menu" id="menu-main-menu">
    <li class="parent selected" id="menu-item-1172">
       <p><a href="http://localhost/portfolio/" style="color: rgb(57, 57, 57);">Portfolio</a></p>
    <div>
       <ul class="sub-menu">
           <li class="menu-item" id="menu-item-1158"><p><a data-filter="website-design" data-category="true" href="#">Website Design</a></p></li>
           <li class="menu-item" id="menu-item-1157"><p><a data-filter="print" data-category="true" href="#">Print</a></p></li>
           <li class="menu-item selected" id="menu-item-1156"><p><a data-filter="motion" data-category="true" href="#">Motion</a></p></li>
           <li class="menu-item" id="menu-item-1155"><p><a data-filter="identity" data-category="true" href="#">Identity</a></p></li>
           <li class="menu-item" id="menu-item-1167"><p><a data-filter="logos" data-category="true" href="#">Logos</a></p></li>
      </ul>
   </div>
   </li>

An attempt was made similar to this solution, but proved ineffective due to the lack of content within the list item. Below is the jQuery code implemented:

/*Portfolio links remove selected CSS setting*/
    $('ul#menu-main-menu ul.submenu li p a').click(
        function(){
            $('ul#menu-main-menu li').removeClass('parent selected');
            $(this).addClass('parent menu-item');
    });

I seem to be at an impasse as I try to achieve the desired HTML structure shown below (removing the CSS class 'selected' and introducing the CSS class 'menu-item'):

<ul class="main-menu" id="menu-main-menu">
    <li class="parent menu-item" id="menu-item-1172">
       <p><a href="http://localhost/portfolio/" style="color: rgb(57, 57, 57);">Portfolio</a></p>
    <div>
       <ul class="sub-menu">
           <li class="menu-item" id="menu-item-1158"><p><a data-filter="website-design" data-category="true" href="#">Website Design</a></p></li>
           <li class="menu-item" id="menu-item-1157"><p><a data-filter="print" data-category="true" href="#">Print</a></p></li>
           <li class="menu-item selected" id="menu-item-1156"><p><a data-filter="motion" data-category="true" href="#">Motion</a></p></li>
           <li class="menu-item" id="menu-item-1155"><p><a data-filter="identity" data-category="true" href="#">Identity</a></p></li>
           <li class="menu-item" id="menu-item-1167"><p><a data-filter="logos" data-category="true" href="#">Logos</a></p></li>
      </ul>
   </div>
   </li>

UPDATE: @limelights response appeared successful, although I noticed some conflicting jQuery affecting the link hover effects on the site which may have hindered the outcome of the code found in the scripts.js file of the WordPress template

/* Links roll over effect */
    $('a').each(function(){
        if(!$(this).data('filter') && !$(this).parent().parent().parent().hasClass('pagination'))
            $(this).hoverFadeColor();
    })

Furthermore, I am on the brink of achieving my objective by implementing the following code to keep the internal links open:

/*Portfolio links remove selected CSS setting*/
    $('ul#menu-main-menu li div ul.sub-menu:first li.menu-item p a').click(
        function(){
            $('ul#menu-main-menu > li').removeClass('selected');
            $('ul#menu-main-menu > li').css({'color' : '#222'}).addClass('menu-item');
            $('ul#menu-main-menu li div:first').show();
        });

However, despite progress, it still shows the text appearing chosen like the selected text.

Your assistance is greatly welcomed and appreciated!

Answer №1

Have you observed the expected outcome from this code snippet?

  $('a').each(function(e){
        if(!$(this).data('filter') && !$(this).parent().parent().parent().hasClass('pagination'))
        $(this).hoverFadeColor();
        e.preventDefault();
   })

If not, consider adding e.preventDefault() to fix the issue.

UPDATED 12/10/2012:

To address any issues, modify your click function as shown below:

$('ul#menu-main-menu li div ul.sub-menu:first li.menu-item p a').on("click",function(){
    var linkClicked = $(this);
    $("#menu-main-menu li").each(function(){
        $(this).removeClass("selected").css({'color' : '#888'}).addClass('menu-item');
        $(this).first("div").show();
    });
    linkClicked.css({'color' : '#222'})
});

Answer №2

I made a slight adjustment to your CSS and incorporated some jQuery functions into your HTML page like so:

CSS modification:

Locate line number 67 in your custom.css file and update the code as shown below:

/*Turns link background white and removes border on the left at hover*/
.Light #menu ul.main-menu > li:hover > p > a {
   background:#FFF;
   /*border-left:6px solid #F0F0F0;*/
}

The above snippet should replace the previous one.

To add the jQuery function, insert the following code somewhere in the header or footer of your theme file:

<script type="text/javascript">
$(document).ready(function() {
$("#menu-main-menu li:first").addClass("selected");
$("#menu-main-menu li p a").css("border-left","none");
$("#menu-main-menu li p a").hover(function(){$(this).css("border-left","6px solid #F0F0F0");});
$("#menu-main-menu li").click(function() {
  $(this).addClass("selected");
});
});
</script>

I have tested these changes and they seem to be effective for me. You can view them in action here: http://jsbin.com/ehagal/1

I hope this solution helps you resolve your issue.

Answer №3

If my interpretation is correct, this solution should be beneficial for you, especially if you have the capability to embed any type of script. :)

$('ul#menu-main-menu li div ul.sub-menu li.menu-item p a').click(function(event){
    $('ul#menu-main-menu > li').removeClass('selected');
    alert($('ul#menu-main-menu > li').attr('class'));
    $('ul#menu-main-menu li').addClass('menu-item');
    alert($('ul#menu-main-menu > li').attr('class'));
    event.preventDefault();
});

Hopefully, this meets your requirements! :)

You can experiment with it here on TInker.io

I included two alerts so that you can observe the removal of the class and the addition of a different class. It's essential to specify the appearance of the new class in the CSS.

Answer №4

By incorporating jQuery into your code, you can resolve the issue at hand as long as it mirrors what is shown in Live preview with minimal customization.

$("#menu-main-menu li").click(function(){ 
    $("#menu-main-menu li").removeClass("selected"); 
});

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

Can you identify the attribute used for marking up an HTML code tag?

While examining a website's code to understand how they styled a specific section of their page, I came across the following snippet: <code markup="tt"> I thoroughly checked for any other references to this particular markup attribute ...

What is the best way to implement next and previous buttons in a slideshow using code?

Looking to enhance my slideshow by replacing the standard "Next" and "Previous" text buttons with custom JPEG images I've created. Anyone familiar with the steps needed to make this switch in the HTML code? Current HTML code in use: <body sty ...

What is the best way to target an HTML attribute using jQuery?

I have customized a Textbox by adding a special attribute: <asp.TextBox MyCustomAttribute="SomeValue"><asp.TextBox> Now, I want to retrieve this value from within an AJAX success function. Please note that I have excluded irrelevant attribut ...

What steps can I take to fix the issues on Safari that are being caused by three js on my website?

For my friend's birthday, I decided to surprise him by creating a web page for his online radio station. Being new to JavaScript, it was a great learning opportunity for me. After much experimenting, I finally got the page to work smoothly on desktop ...

What causes errors in jQuery ajax jsonp requests?

"fnServerData": function( sUrl, aoData, fnCallback, oSettings ) { oSettings.jqXHR = $.ajax( { "url": sUrl, "data": aoData, "success": fnCallback, "error":function(msg){ ...

What is the best method for incorporating multiple jQuery ready() functions?

Trying to develop a web application with HTML files that require multiple JS files. Need to specify tasks inside jQuery.ready() in each JS file, but unable to define $(function () {}) more than once. Is there a way to modify the passed function? index.pug ...

CSS failing to reach the full width of the container

My navigation tab is currently only occupying half of the width that I need it to. I have tried various solutions found on this site and through Google, but none seem to work as expected. The black background of the navigation should fill up 100% of the wi ...

I am having trouble getting Highcarts to load the JSON data

I am currently in the process of utilizing Highcharts to generate a chart. The JSON output I have is in standard format and was generated using PHP's json_encode() function. Below is the JSON output: [["2015-07-13 16:41:05","3"],["2015-08-15 16:41:05 ...

Having trouble transferring a JQuery variable to PHP - what am I doing wrong?

Trying to transfer a jQuery variable to PHP, here is the code <label>Turnamen</label> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <input id="checkturnamen" ...

What could be the reason for event.stopPropagation() not functioning properly with a switch statement

Could you please explain why the function event.stopPropagation() is not working on the switch element? Whenever I click on the switch, it prints the console log for the switch. However, when I click on the surrounding area (row), it logs the row event in ...

What is the best way to conceal a modal using jquery?

Click button to open modal: <button type="button" class="btn" onclick="CountClass()" runat="server" data-toggle="modal" data-target="#inlineForm1">OPEN</button> The modal code: <div class="modal fade text-left" id="inlineForm1" tabindex=" ...

Alternative to CSS Clip path for creating an accordion styling

I'm attempting to create an accordion that expands from the view shown below. https://i.sstatic.net/D3LJP.png To. https://i.sstatic.net/cjG6z.png It should open or close by clicking on a 'Project' thumbnail, which is displayed in the top ...

A button featuring an extensive label that utilizes text-overflow ellipsis is initially set with a max-width of 700px. However, it should dynamically shrink when the viewport size decreases

My Request I need a button that can accommodate both long and short labels, with the text getting cut off at 700px using ellipses. The button should adjust to the available space when the viewport is smaller than 700px. The length of the label can vary gr ...

CSS animation fails to animate the object

I am encountering an issue with a CSS animation that I am trying to implement for each child within a nav element. Specifically, I am attempting to create a dynamic stock panel. Interestingly, when I add another CSS attribute like color, it works as expec ...

The Conundrum of CSS versus Razor Views

Currently, I am developing a basic website using ASP.NET/MVC with Razor (.cshtml). As I am relatively new to CSS, I am interested in customizing the appearance and style of my site. After inspecting the source of the homepage, I find myself struggling to t ...

Transitioning smoothly from one specific location to another through a scrolling motion

Imagine having a box that is currently off from its correct position due to tranform:translateX(-200px) https://i.sstatic.net/2Mgwm.jpg Just below the picture, there are two <section>'s displayed - one as a large grey box and the other as a whi ...

How can I restrict the navigation buttons in FullCalendar to only allow viewing the current month and the next one?

I recently downloaded the FullCalendar plugin from Is there a way to disable the previous button so that only the current month is visible? Also, how can I limit the next button so that only one upcoming month is shown? In my header, I included this code ...

Position navbar contents at the top of the screen

As I delve into learning Bootstrap4, I have come across the following snippet of HTML code: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> ...

Eliminating padding or margin for figures in Bootstrap on smaller screens

I've been struggling to create a fullscreen image on small devices without any margin or padding. Unfortunately, the solutions suggested in this thread didn't work for me. Below is the code I'm currently using (tested on https://jsfiddle.n ...

Set the container width to a fixed size, then center a div within it with a dynamic width. Ensure that the left and right div

Arrange three columns with a fixed combined width. The center column will have dynamic content, while the left and right columns should fill out the remaining space equally. For example, see this demonstration: http://jsfiddle.net/htKje/ <div class="c ...