Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm using a starter theme that was provided to me by a friend, and have successfully implemented jQuery several times on the website. I want a background image inside a div to change when the user click a li in the menu.

<ul class="mainNav">
    <?php wp_nav_menu( array( 'container' => false, 'theme_location' => 'primary' ) ); ?>
</ul>

$(function(){
$('.menu-item-23').click(function(){
  $('#changeMe').css('background-image','url("../wp-content/themes/theme-name/i/logo4.png")');
});

I am able to make this work if I replace .menu-item-23 with other elements on the page - so I know it isn't a file path issue, and I don't think it's the jQuery code. It seems like I'm not selecting the list item properly, but I have tried dozens of different selectors, (li#menu-item-23, li.menu-item-23, ul.mainNav li#menu-item-23 etc etc)

share|improve this question
    
First, your jQuery needs to be set to use noConflict wrappers, –  helgatheviking Aug 14 at 23:38
    
menus are usually links and will cause a page refresh that will remove your CSS changes. –  Mark Kaplun Aug 15 at 2:54

2 Answers 2

  • You are missing <script> tags
  • You are using the wrong jQuery variable name. If you want to use the $ alias you need to use noConflict as helgatheviking suggested or switch to "jQuery" instead of $
  • You are missing }); at the end of the code you posted above
  • You should consider separating your JS into a separate file and use wp_enqueue_script in the theme's functions or other appropriate theme or plugin PHP file
share|improve this answer

The answer by Bjorn has some very good points, but I would avoid the javascript entirely, and use css similar to this:

.mainNav li:active {
    background-image: transparent url('i/logo4.png') no-repeat;
}

Better yet, I would instead target the link itself using .mainNav a:active, which suggests your link targets aren't very large and you're using the li not the a to define the dimensions and size/padding/margin

There's no need for javascript at all here

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.