-2

I have been working on a screen greyout script in jQuery. It works in the link below on my jsFiddle, but the code below from my WordPress plugin does not work.

https://jsfiddle.net/jblevins1991/8ts25q2v/1/

PHP code to include javascript:

function myScripts() {
    wp_enqueue_script('myScript', plugins_url('myPlugin/JS/myScript.js'), array('jquery'), true);
}

add_action('wp_enqueue_scripts', 'myScripts');

HTML code:

<div id="box"></div>
<img id="something" src="http://www.w3schools.com/images/w3schools.png" />

The jquery from myScript.js file:

$(document).ready(function() {
    $('#something').click(function() {
        $('#box').show();
        $('#box').fadeTo(500, 0.5);
    });
});
8
  • Is your javascript even being rendered? Check your html source first. Commented Sep 15, 2015 at 18:59
  • Debug your code. console.log($('#something')); from inside the document ready. Does it find an element? Add a line inside of the click, is it called? Does it find box? Also weird you show and do fadeTo. Are there errors in the console? Commented Sep 15, 2015 at 19:01
  • All other normal javascript code is working. It is literally everything related to jquery. I have tried checking to see if jquery is loading on the page and it is in the header. I also used jslint to make sure that it was valid jquery code. Commented Sep 15, 2015 at 19:01
  • I highly doubt that it is my code. I think it's more on the wordpress side of things. I say that because it works in a normal html page, jsfiddle, but not wordpress. Commented Sep 15, 2015 at 19:04
  • Is jQuery included before or after myScript? Commented Sep 15, 2015 at 19:05

1 Answer 1

1

Try to use the following JavaScript code instead:

jQuery(document).ready(function($) {
    $('#something').click(function(){
        $('#box').show();
        $('#box').fadeTo(500, 0.5);
    });
});

It's basically wrapping your code in a No Conflict wrapper because using $() might return undefined otherwise.

Sign up to request clarification or add additional context in comments.

2 Comments

You sir are just wonderful! Thank you for the solution.
To put a sharper point on this answer: WordPress loads jQuery in no-conflict mode. You can not access jQuery via $ without using a no-conflict-safe document ready. An alternate shorthand no-conflict-safe jQuery document ready is simply jQuery(function($) { // .. $ is safe in here ... });

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.