Search code examples
javascriptcsswordpressmenubold

Menu element bold when coming on page and bold another menu element on click wordpress


I've been searching a long while for the answer but haven't found a good solution. I want the menu item DE to be bold when I enter the site and if I click on EN I want the DE to be thin again and the EN bold.

the site is : https://kxplaw.live-website.com

For now I managed to display the element with class current-menu-item in bold but that doesn't include the element when I open the page first.

I have tried things with Javascript but I'm not so sure on how to make it work.


Now it still doesn't work - unfortunately. In my JS, I have the following:

jQuery(document).ready(function($) 
{ 
  jQuery(document).on("click", ".menu-language", function(){
  var lang = jQuery(this).text();
  sessionStorage.setItem("language", lang);
});
  var language = sessionStorage.getItem("language") ?? 'DE';
  if(language != null) {
  jQuery(".lang-" + language).css({"font-weight": "bold"})
} 
});

The problem now is that I have to click twice on DE or EN so that it becomes bold. Does anyone know what I could do in this case? And it isn't bold on DE by default.


Solution

  • Go to Appereance -> Menus, and in upper right corner click on Screen Options. Then (if not checked) check option CSS Classes, and for every menu item now you have new field CSS Classes (optional) and add class menu-language for EN and for DE

    And only for DE add class lang-DE

    And only for EN add class lang-EN

    And now attach on ti click event

    // On click will add session storage language param
    jQuery(document).on("click", ".menu-language", function(){
        var lang = jQuery(this).text();
        sessionStorage.setItem("language", lang);
    });
    
    // On every page load we check lang param and than we bold selected language
    // Default value will be "DE"
    var language = sessionStorage.getItem("language") ?? 'DE';
    if(language != null) {
        jQuery(".lang-" + language).css({"font-weight": "bold"})
    }
    

    And now on every page selected language will be bold.