Link to home
Start Free TrialLog in
Avatar of Nura111
Nura111

asked on

understanding jquery

Im having a hard time understanding what happen "behind the scenes" of the jquery code
I attched a simple jquery code .
what happening when creating the function()  when do I need to create it I understand that $ is actully built a new query object and that  and when you call a function .functionName its a method that dec declared in jquery class/object

Thank you!
$(document).ready(function(){
   $("a").click(function(event){
     alert("As you can see, the link no longer took you to jquery.com");
     event.preventDefault();
   });
 });

Open in new window

Avatar of guru_sami
guru_sami
Flag of United States of America image

Avatar of Nura111
Nura111

ASKER

I already read a few tutorial and still didnt understand it I was hoping for an explanation from the experts..
ASKER CERTIFIED SOLUTION
Avatar of crysallus
crysallus
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Nura111

ASKER

what about when its a function that fired up does it still need to be wrapped in $(document).ready(function())

because if its fired up by a user click for exmple its sure that the document is ready right?
Yes. Good point. As far as I understand, event driven jQuery code doesn't need to wrapped in the ready method.
Avatar of Nura111

ASKER

".click(function(event){...});

Having created a jQuery object containing all anchor tags, the click method is called on them. The click method is a shorthand event adding method that wraps the jQuery bind method. There are several other shorthand event functions, hover etc. Internally they all call the bind method which attaches a function to a particular event. The bind method can also be used directly if you wish, to achieve the same effect. eg.

.bind('click', function(event){...});

will do the same thing."



so for exmple here when creating a function() in the click() its binding the click with this function meaning that when a click will happen on the element (in this case a )  this function will fired up as well?
Yes.
Avatar of Nura111

ASKER

thank you for the nice explanation

Can you also take a look on the next question about jquery:
https://www.experts-exchange.com/questions/27344572/how-to-get-the-value-of-a-specific-field-using-attr-or-other-in-jquery.html
To clarify your question in #36713290
When you bind an element to some event, you should place it in the $(document).ready(function(){});
i.e. $("#somebutton").click(function(event){...});
should go inside document.ready. Why because you are doing $("#somebutton") i.e. finding element with id #somebutton. You want to make sure that the element is available when the binding statement is executed.

But if you have a stand alone function like: function Add(x,y){} it does not need to be in document.ready..