Rubén Jiménez
Rubén Jiménez

Reputation: 1845

jQuery.Click method reloads the page

I'm trying to creating a floating div who shows up when a button is triggered. It's not hard, but when i press the button the page automatically reloads. I don't know why.

I tried to use Bootstrap's Popover, but it doesn't working as expected due to this same problem. When the popover is triggered, the page reloads and the popover obviously disappear.

I'm using RoR, just saying in case that would be useful to find out the problem.

I have something like this in document's bottom:

<a href="#" class="btn btn-small btn-warning" id="example">Show</a>

<script type="text/javascript">
    $(document).ready(function() {
        console.log("Page is loaded.");

        // Custom Popover
        $("#example").click(function() {
            console.log("Showing");
        });
    });
</script>

The first console.log inside ready function is shown when the page loads. When I trigger the button "Show", that console.log is again shown in browser's console. And that doesn't make any sense.

Thanks!

Upvotes: 4

Views: 13605

Answers (6)

Tyro Hunter
Tyro Hunter

Reputation: 755

you have to stop the anchor to do it's default function, loading the page specified its href. This code should do the trick:

$("#example").click(function(event) {
     event.preventDefault();
     console.log("Showing");
});

Upvotes: 1

Rameez
Rameez

Reputation: 1712

This can't be, it should work fine. There must be some other issue, please jsfill of your full page.

 $(document).ready(function() {

  console.log("Page is loaded.");

  // Custom Popover
  $("#example").click(function() {
      console.log("Showing");
  });

});

See here

Upvotes: 1

kappatech
kappatech

Reputation: 498

Here you can find a fully working example. test here

$(document).ready(function()
{
   console.log("Page is loaded.");

   $("#example").click(function(e) 
   {
      e.preventDefault();
      alert("works");
   });

});

Upvotes: 1

Andr&#233; Dion
Andr&#233; Dion

Reputation: 21708

You have two issues:

You're setting your classes in your href attribute instead of class

<a href="#" class="btn btn-small btn-warning" id="example">Show</a>

You'll want to stop your browser from following the href when the link is invoked:

$("#example").click(function( e ) {
    e.preventDefault(); // don't follow href
    console.log("Showing");
});

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

You need to stop the default behaviour of the link by using preventDefault():

$("#example").click(function(e) {
    e.preventDefault();
    console.log("Showing");
});

Upvotes: 16

Arun P Johny
Arun P Johny

Reputation: 388316

you have a problem, instead of class you have used href

<a href="#" class="btn btn-small btn-warning" id="example">Show</a>

Upvotes: 1

Related Questions