简体   繁体   中英

Javascript and wordpress page load

Am working on a website techhouse.ng. My problem is that I have a javascript that changes the width and color of certain divs when the menu li links (services and contact) are clicked. The script works fine but the problem is that by the time the page loads the divs reverts back to the default settings.

I created page-service.php and page-contact.php for those links. but the script works on the index.php, so when you click on either the services link or the contact links the script works but by the time the page loads the divs revert back to their original css values.

 jQuery(document).ready(function ($) {

 $("#li-12").click(function () {
 $("#rcolumn").css("width", '25%');
$("#rcolumn").css("background-color", 'rgb(44, 62, 80)');
$(".wrapper").css("background-color", 'rgb(44, 62, 80)');
$(".nav li a").css("padding", '15px 0');
$(".nav li a").css("color", '#909090');
$(".nav li a").css("background", 'white');
$("#lcolumn").css("width", '75%');
$(".nav").css("width", '75%');
});

$("#li-13").click(function () {
$("#rcolumn").css("width", '25%');
$("#rcolumn").css("background-color", 'rgb(44, 62, 80)');
$(".wrapper").css("background-color", 'rgb(44, 62, 80)');
$(".nav li a").css("padding", '15px 0');
$(".nav li a").css("color", '#909090');
$(".nav li a").css("background", 'white');
$("#lcolumn").css("width", '75%');
$(".nav").css("width", '75%');
}); 

});

First, you can combine multiple selectors like this: $("#li-12, #li-13") so your can remove a lot of duplicate code.

Second, to get the styling on those 2 pages you could put the .css stuff inside a named function and call it... though it's far from ideal, as it will have to wait until jquery framework is loaded, meaning the user will first see the default style until jQuery kicks in. It could be done using pure javascript which would fire sooner. A lot better would be to put style tags on those 2 templates, to override the default styles. Or use classes to do stuff.

But if you don't mind the delay you could do something like this:

jQuery(function($) { //.ready

  function altStyling() {
    $("#rcolumn").css("width", '25%');
    $("#rcolumn, .wrapper").css("background-color", 'rgb(44, 62, 80)');
    $(".nav li a").css("padding", '15px 0');
    $(".nav li a").css("color", '#909090');
    $(".nav li a").css("background", 'white');
    $("#lcolumn, .nav").css("width", '75%');
  }

  // click menu items
  $("#li-12, #li-13").click(altStyling);

  // call if we're on services or contact page
  if (location.pathname == "/services/" || location.pathname == "/contact/") altStyling();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM