1

I'm using jQuery replaceWith to replace a visible <div> with another. However for some reason when I click the link to initiate the replaceWith, the page reloads and causes the original <div> to appear again. Here's my jQuery:

$(function(){
    $("a#startSlide").click(function () {
        $('div#leftText').replaceWith('div#slide');
    });
});

Why is this reloading after the div is replaced?

tvalent2
  • 4,959
  • 10
  • 45
  • 87

3 Answers3

3

You need to cancel the event, since the default event for an anchor click is to change the window location:

$(function(){
    $("a#startSlide").click(function (event) {
        event.preventDefault();
        $('div#leftText').replaceWith('div#slide');
    });
});
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
  • Won't returning false do the same thing? – Paul Tomblin Oct 22 '11 at 22:07
  • I prefer not to return false. The intention of the code does not obviously imply the behavior of the code, whereas `event.preventDefault()` does exactly what it says and novice devs don't have to guess what it is trying to do. – AlienWebguy Oct 22 '11 at 22:12
  • @AlienWebguy: `return false;` would be preferable if you have `$('a').click(function() { /* do ajax loading */ })` elsewhere, otherwise your second handler will still execute. – Eric Oct 22 '11 at 22:22
  • `return false` won't prevent your example from firing. Its two binds. – AlienWebguy Oct 22 '11 at 22:35
  • @AlienWebguy: I have a similar problem as tvalent2 except if I use preventDefault it wont do anything at all. My code is the following: var html =
    $('#container').replaceWith(html); inside a script tag for
    – EBM Nov 24 '12 at 01:41
0

You need to either return false or preventDefault().

$(function(){
    $("a#startSlide").click(function (e) {
        e.preventDefault();
        e.stopPropagation();
        $('div#leftText').replaceWith('div#slide');
    });
});

OR

$(function(){
    $("a#startSlide").click(function (e) {
        $('div#leftText').replaceWith('div#slide');
        return false;
    });
});
Ivan
  • 10,052
  • 12
  • 47
  • 78
0

Your <a> tag presumably has a href="#". This reloads the page when clicked.

When you bind your event handler, you need to cancel your default behaviour:

$(function() {
    $('a#startSlide').click(function() {
        $('div#leftText').replaceWith('div#slide');

        return false;
        //equivalent to:
        //  e.preventDefault();
        //  e.stopPropagation();
    });
});

Alternatively, you could change your <a> tag to be href="javascript:void()".

Eric
  • 95,302
  • 53
  • 242
  • 374