3

I'm working on a project where I'm using a lot of ajax calls to make the the site interaction more elegant. The process I have been using is to have the link to the script that executes the appropriate action stored as the href in a link tag. I then use jquery to target that element and disable the default action and execute the ajax call.

The problem is that on occasion the $(document).ready() function doesn't properly execute or is delayed in executing before a user can click the links. This results in the page being opened via normal browser load.

I have implemented code that detects if the code is being executed via ajax or via the browser so all that happens is that a blank page is loaded. In some cases I can have it detect the execution type and respond differently but in other cases, if it's not executed by ajax then it causes problems.

Is there a way to ensure that the link's default action is disabled at all times regardless of the page's loading progress or is there a better approach than the one I'm taking?

JJJ
  • 32,902
  • 20
  • 89
  • 102
Kenneth
  • 589
  • 6
  • 18
  • possible duplicate of [Href for JavaScript links: "#" or "javascript:void(0)"?](http://stackoverflow.com/questions/134845/href-for-javascript-links-or-javascriptvoid0) – samjudson Feb 06 '12 at 13:11

6 Answers6

3

Why not use some code like this:

<a href="javascript:void(0)" onclick="myJsFunc();">Link</a>

Taken from: Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

Community
  • 1
  • 1
thedjpetersen
  • 27,857
  • 4
  • 26
  • 28
  • it is not ideal, but i think it is the best solution for this case. – Grace Huang Feb 01 '12 at 19:36
  • @GraceShao Why do you say it's not ideal? – Kenneth Feb 06 '12 at 19:27
  • @Kenneth I'm not a big fan of Pseudo-Protocol (put JavaScript in the href) see http://www.javascripttoolbox.com/bestpractices/#onclick. Maybe `Link` is much better. – Grace Huang Feb 07 '12 at 04:37
  • @Kenneth Some people don't think it's ideal because html event tags don't fit the MVC (model view controller) philosophy. In this philosophy, all functionality is placed in JavaScript files. – Scott Tesler Dec 13 '12 at 05:15
3

You can run the code in the global scope, just place the JS code block after the DOM elements (links) you are working with. This way you aren't relying on an event handler to fire. Placing the code block just before the closing </body> tag is good place.

    <a class="my-links" href="/path/to/server-side.***"></a>
    <script>
    function myFunc () {
        $.ajax({
            url     : $(this).attr('href'),//use the href attribute for the link clicked as the URL for the AJAX request
            type    : 'get',
            success : function (serverResponse) {
                alert('Success');
            },
            error   : function () {
                alert('Error');
            }
        });

        //in a jQuery event handler, returning false is the same as calling: event.preventDefault(); event.stopPropagation()
        return false;
    }
    $('.my-links').bind('click', myFunc);
    </script>

</body>
Jasper
  • 75,717
  • 14
  • 151
  • 146
  • This will not trigger other `click` handlers. – ShankarSangoli Feb 01 '12 at 19:26
  • Definitely be cautious of using this. This would effectively disable onclick in all anchor tags in your page. – sinemetu1 Feb 05 '12 at 04:14
  • @sgarrett it would only disable links with class "my-links" – Kenneth Feb 06 '12 at 19:26
  • @Kenneth I updated my answer after ShankarSangoli and sgarrett's comments. My first edition was just a demonstration of how to run some code outside of a `document.ready` event handler (the OP seemed to already have created a function to bind to the events but I added some demo code anyhow). – Jasper Feb 06 '12 at 19:34
1

One thing I can think of is to set the href value to a hash. This will cause a clicked link to essentially do nothing. You could then store the url in a data attribute instead.

<a href="#" data-url="http://..." >go</a>

 

$('a').click( function() { 
    var url = $(this).data('url'); 
});
mrtsherman
  • 39,342
  • 23
  • 87
  • 111
  • 2
    Sometimes I don't like the # solution, which messes up the scrollbar - the scrollbar will always go to the top after you click it. So this link still is considered as triggering an action. – Grace Huang Feb 01 '12 at 19:35
  • You can just have the click event's function return false to prevent the page jump behavior. Or you can use event.stopPropagation() – Jim Jeffers Feb 02 '12 at 06:33
0

Try this.

$('a').click( function(e) { 
    e.preventDefault();
});
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
0

If you're looking to prevent default action from the html then something like this will work:

    <a onclick="some_function(); return false;"></a>

This doesn't pollute your url with # and you don't have to set a href attribute on the element. This solution is essentially the same as using event.preventDefault(); in a click event function with jQuery.

sinemetu1
  • 1,726
  • 1
  • 13
  • 24
0

The challenge here is remaining unobtrusive. One way to do this would be to use html5 data-attributes. What you could do is specify the href to the links as such:

<a href="#" data-href="actual/file/path.html">

Then in your document.ready you can swap the data attribute contents into the href attribute or just have your click handler use the data attribute instead of the href attribute. This way if the user clicks a link prior to your javascript bindings nothing will happen. To swap all of the data-href attributes info the appropriate hrefs just use jquery:

$(document).ready(function(){
   $("a[data-href]").each(function(){
      $(this).attr("href",$(this).attr("data-href"));
   });
});
Jim Jeffers
  • 17,572
  • 4
  • 41
  • 49