Javascript included but alert() function not working

I’ve included the javascript by

wp_enqueue_script('slider', plugins_url( 'slider.js', __FILE__ ) );

with just a simple

$(document).ready(function () {
    alert("alert");
});

It shows up in the browser but doesn’t prompt me with “alert”.

PS: Forgot to mention I’ve also included the jquery, but still not working.

wp_deregister_script('jquery');
wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);
wp_enqueue_script('jquery');

In addition to the answers, I also had to tell wordpress that my script depends on jQuery

wp_enqueue_script( 'slider', plugins_url( 'slider.js', __FILE__ ),array('jquery') );

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

A few things:

  1. The version of jQuery that ships with WordPress is run in noConflict() mode. Meaning you have to use jQuery instead of $ when you make your first reference.
  2. Don’t register your own version of jQuery when you’re developing. You’re locking yourself in to a single version that may or may not be compatible with WordPress’ other requirements.
  3. You can use the browser console to test things. Open your page, then hit F12 to launch the console. Type jQuery into the console and see whether or not it returns the correct object.

Method 2

WordPress loads jQuery in “No Conflict” mode. The $ alias does not work. Use jQuery.(document) or wrap your code like…

(function($) { 
  $(function() {
    // more code using $ as alias to jQuery
  });
})(jQuery);

Method 3

It is worth to check according to the Bootstrap .js declaration if required (after jQuery) i.e.

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x