0

I want to write a JavaScript function and invoke it on a this object in this way:

<div id= 'MyDiv'>screamer</div>

function scream()
{
   if(this.hasClass("scream")) {
      alert("scream");
   }
   else {
      alert("shhhh");
   }
}
$(function () {
   $('#MyDiv").scream();

}

Here is the jsfiddle: http://jsfiddle.net/JtN9W/

What am I doing wrong?

2
  • 1
    It seems you want to create a jQuery plugin. Read this: learn.jquery.com/plugins/basic-plugin-creation. There are other problems though, e.g. you are using mismatched quotation marks: $('#MyDiv"). Commented Nov 24, 2013 at 20:23
  • you can also give a try to book Extending JQuery Commented Nov 24, 2013 at 20:29

4 Answers 4

4

scream is a global, so it is a property of the window object and not the jQuery object that you've created.

If you want to attach it to every jQuery instance then you need to assign it to $.fn.something

function scream() {
    //etc
}
$.fn.scream = scream;
Sign up to request clarification or add additional context in comments.

Comments

0

Like this:

jQuery.fn.scream = function() {
    if(this.hasClass("scream")) {
        alert("scream");
    } else {
        alert("shhhh");
    }
}  
$(function () {
     $('#MyDiv').scream();
});

jsfiddle: http://jsfiddle.net/JtN9W/2/.

Comments

0

In your code there are more error:

  1. I change you code with replace ' to " but you can use also this character '
  2. The function scream you can't call with jquery using $('#MyDiv").scream(); I change this in

     $(function () {
           scream($("#MyDiv"));});
    

And I don't know how to use this call $('#MyDiv").scream(); and I change your code passing the div

DEMO

Comments

0

You have to make your own object, follow jQuery api manual: http://learn.jquery.com/plugins/

Solution for you:

(function ( $ ) 
{
  $.fn.scream = function() 
  {
    var c = $(this);

   if(c.hasClass("scream")) {
      alert("scream");
   }
   else {
      alert("shhhh");
   }

    return this;
  };

}( jQuery ));

$(function () {
   $('#scream').scream();
     });

HTML markup:

<div id="scream" class="screaam"></div>

Working example: http://jsfiddle.net/qPgA9/

Cheers!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.