JQuery.Click method reloads page

I am trying to create a floating div that appears when a button is clicked. It is not difficult, but when I click the button, the page automatically reloads. I do not know why.

I tried using Bootstrap Popover, but it does not work properly due to the same problem. When the popover starts, the page reloads, and the popover obviously disappears.

I use RoR, just saying in the case that it would be helpful to find out the problem.

I have something like this at the bottom of the document:

<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 function inside the finished function is displayed when the page loads. When I run the "Show" button, this console.log is displayed again in the browser console. And that makes no sense.

Thanks!

+4
source share
6 answers

You need to stop the default link behavior using preventDefault() :

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

you have a problem, instead of class you used href

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

You have two problems:

You set your classes in your href attribute instead of class

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

You want your browser to not follow href when the link is called:

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

you need to stop the binding in order to execute it by default, loading the page specified in href. This code should do the trick:

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

This cannot be, it should work fine. There must be some other problem, please jsfill your full page.

  $(document).ready(function() { console.log("Page is loaded."); // Custom Popover $("#example").click(function() { console.log("Showing"); }); 

});

See here

+1
source

Here you can find a fully working example. check here

 $(document).ready(function() { console.log("Page is loaded."); $("#example").click(function(e) { e.preventDefault(); alert("works"); }); 

});

+1
source

Source: https://habr.com/ru/post/1500729/


All Articles