Question

I know there are many posts about there regarding preventDefault() not working but I went to those and got nothing out of it.

All I'm doing is catching a click event and then appending the html from the response but preventDefault() isn't stopping the page from reloading and I'm confused why.

Here's my HTML:

<div class="slide_pane"> 
 <div class="profile_content"></div>

 <div class="account_bottom_bar">
  <ul class="bottom_bar_list">
    <a href="/profiles/load" class="sidebar_link">
      <li>
        <p>Content</p>
      </li>
    </a>
  </ul>
 </div>

And here's my JS:

$(document).scroll(function() {
 ajaxView();
});

var ajaxView = function() {
 $('.sidebar_link').click(function(e) {
 e.preventDefault();
 $.ajax ({
  type: 'GET',
  url: $(this).attr("href")

  }).done(function(resp) {
   $('.profile_content').append(resp);
  });
 });
};

But when I hit that action, it just loads the HTML from the response in a new screen.

Any ideas?? Thanks!

Was it helpful?

Solution

Nothing happens because there is no sidebar_link in your HTML.

Example use of event.preventDefault():

$(document).ready(function() {
    $(".sidebar_link").click(function(event) {
        event.preventDefault();
        $(this).css("color", "red");
    });   
});

Here is an example how to use event.preventDefault() on links: http://jsfiddle.net/LUKVT/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top