0

This is the jquery

$( document ).ready(function() {

    $( "a" ).click(function( event ) {

        alert( "Hi!" );

        event.preventDefault();

    });

});

within the function event is a parameter to which we could replace it with whatever and we could do as this whatever.preventDefault() but I would like to know without inserting any parameter like function() could we do only this .preventDefault(); does this work?

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231

5 Answers5

1

No, your code can't work if you don't specify a parameter to the function because a method can't be applied to nothing.

Lucas Willems
  • 6,673
  • 4
  • 28
  • 45
1

No, the preventDefault() function is associated with the event.

so you should have

$(document).ready(function () {
    $("a").click(function (event) {            
        event.preventDefault();
    });
});

or

you can use return false

$(document).ready(function () {
        $("a").click(function () {            
            return false;
        });
    });

return false from within a jQuery event handler is effectively the same as calling both e.preventDefault on the passed jQuery.Event object.

Check this SO Answer

Community
  • 1
  • 1
Praveen
  • 55,303
  • 33
  • 133
  • 164
0

Yes, You can do that. see below code:

 $( "a" ).click(function() {
      alert( "Hi!" );
 }).preventDefault(); //add .preventDefault() here
Code Lღver
  • 15,573
  • 16
  • 56
  • 75
0

Your event parameter is as a matter of fact jQuery event data object. It represents state of the event along with its control points.

If you don't have this, you can't control what you want.

OzrenTkalcecKrznaric
  • 5,535
  • 4
  • 34
  • 57
0

You can capturing event to, usefull to delegate event:

var eventToPrevent = "click",
    selectorToPrevent = "a";

document.addEventListener(eventToPrevent, function (e) {
    if ($(e.target).is(selectorToPrevent)) e.preventDefault();
}, true);

DEMO

A. Wolff
  • 74,033
  • 9
  • 94
  • 155