Jquery - block specific links before the page is fully loaded and will link click events

I have a modal dialog plugin written in jquery that binds to the click event for all <a> elements with a specific class.

The modal dialog "selects" the page through AJAX, which is declared under the "href" parameter in the <a> element.

Everything works fine, but - when the user presses the <a> button before the page has been fully loaded and ready (before the click event is attached to the element) - the browser goes to the page declared in the "href" parameter.

Any ideas on how to prevent this behavior? An ideal situation would be to ignore clicks on these elements until the page is fully loaded. Client-side performance is critical.

+4
source share
2 answers

If you need to avoid inline scripts, you can use the jQuery live () method to bind an event handler for elements that have not yet been added to the DOM:

1) Be sure to include jQuery in <head> and not <body> , since we need to initiate the following code before any elements in the body are created.

2) Include the following, also in <head> (for example, as an external js file):

 $("a").live("click", function(){// Use a more specific selector than "a" if poss. getAjax( // This is your Ajax function. Adapt as required. $(this).attr('href') // Pass in the <a> href attribute. ); return false; // Cancel the default click handler, to prevent page redirect. }); 
+3
source

Usually you avoid directly encoding any href in the tag. Instead, set href = "javascript: void (0)" and process the view using jQuery.

Do something like this:

 <a onclick="SomeJQueryCall()" href="javascript:void(0)">Click Me!</a> 

And here is the jQuery script:

 function SomeJQueryCall() { //ask the web server for some AJAX xml $.get(SomeUrl, null, SomeCallBackFunction(), "xml"); } 
+3
source

All Articles