0

I'm currently loading my page data dynamically clicking on an element like this:

<a onclick="load('url_of_data')">Some Text</a>

But for a better UX I now want to have an element like this:

<a href="url_of_data">Some Text&</a>

and then just use preventDefault like this;

$("a").click(function(e){
    var self = $(this);
    var href = self.attr('href');
    e.preventDefault();

    load(href);         
});

I got this code from this question.

But it does not work, the site is still reloading and not running the function.


I now apply the click handler everytime the dynamic content was loaded and it works fine.

  • Where is the code for `load()`? What errors are thrown? Give a proper explanation of what should happen....broken code is not a good substitute for an explanation – charlietfl Jun 19 '17 at 10:24
  • When the `a` tag itself was dynamically loaded, you either have to reapply the click handler or you have to use jquery's `on` function overload with the additional selector argument. – Patrick Günther Jun 19 '17 at 10:31
  • Okay you are right, I now also added the click() event in the load() function and it works, thank you – Alexander Kutschera Jun 19 '17 at 11:08

5 Answers5

0

You will need to specify the container div to which the content will be loaded into.

$("a").click(function(e){
    var self = $(this);
    var href = self.attr('href');
    e.preventDefault();

    //Replace "self" with the container you want to load the content into, e.g. $("#myDiv").load(href);
    self.load(href);         
});
Marcel Wasilewski
  • 2,519
  • 1
  • 17
  • 34
0

You need to add return false at the end of your function

$("a").click(function(e){
   var self = $(this);
   var href = self.attr('href');
   e.preventDefault();

   load(href);
   return false;         
});
Victor Leontyev
  • 8,488
  • 2
  • 16
  • 36
0

I Think this will make the work.

$('a').click((e) => {
    e.preventDefault(); 
    const href = $(e.currentTarget).attr('href');

    window.location.href = href;
});
Eyal Cohen
  • 1,188
  • 2
  • 15
  • 27
0

I just needed to reapply the click handler everytime the dynamic content was loaded.

Now it's working fine

-1
$("a").click(function(e){
   var self = $(this);
   var href = self.attr('href');

  window.location.assign(href);
});

It helps you

Neeraj Pathak
  • 759
  • 4
  • 13