brietsparks
brietsparks

Reputation: 5006

Wordpress JQuery not working

I have enqueued my js file in WP which shows up in the page source as:

<script type="text/javascript" src="http://localhost/yhomh/wp-content/themes/responsive-child/js/menu.js?ver=3.9.2"></script>

The js code is supposed apply the class "first-half" to the first half of all <li> elements under <ul id="menu-main">. The code I have is:

$(document).ready(function(){

    var menuItems = $("ul#menu-main li");

    menuItems = menuItems.slice(0, Math.floor(menuItems.length/2)).addClass("first-half");

});

The code does not work. Please help me find where I made a mistake. As a beginner to jquery, I would appreciate any help possible, thanks!

Upvotes: 0

Views: 66

Answers (3)

Manwal
Manwal

Reputation: 23816

Assuming your jQuery library is loaded perfectly. You can check it in Developer tool. You can check for error in console.

Instead of

$(document).ready(function(){

});

use jQuery no-conflict wrapper

$.noConflict();
jQuery( document ).ready(function( $ ) {
  // Code that uses jQuery's $ can follow here.
});

Upvotes: 0

JayDeep Nimavat
JayDeep Nimavat

Reputation: 476

You have to replace '$' with 'jQuery'.

Some times $ sign not worked so you have to use jQuery keyword like :

jQuery(document).ready(function(){

    var menuItems = jQuery("ul#menu-main li");

    menuItems = menuItems.slice(0, Math.floor(menuItems.length/2)).addClass("first-half");

});

Try it.

Upvotes: 0

adeneo
adeneo

Reputation: 318182

Wordpress is in no-conflict mode by default, so you'll need a no-conflict wrapper, as described in the codex

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

    // code here

});

and make sure jQuery is added as a dependency

wp_enqueue_script( 'handle', '/url/menu.js', array('jquery'), '3.9.2', true );

Upvotes: 1

Related Questions