user1077220
user1077220

Reputation: 1523

It scrolls to the top of the page after clicking

I have this code to switch a switching button image:

$("#invio_scatola_on, #invio_scatola_off").click(function(){
    $("#invio_scatola_off").toggle();
    $("#invio_scatola_on").toggle();
});

when it is executed, the browser goes to the top of the page. why?

Upvotes: 0

Views: 242

Answers (4)

Ankur Verma
Ankur Verma

Reputation: 5933

I think you binded the click on anchor tags with href as # so for that you can use preventDefault() of javascript like :

$("#invio_scatola_on, #invio_scatola_off").click(function(evt){
    evt.preventDefault();
    $("#invio_scatola_off").toggle();
    $("#invio_scatola_on").toggle();
});

Upvotes: 1

acme
acme

Reputation: 14856

I can only guess, because you didn't post your html code. Most probably your two elements are links with href="#". After you click handler the regular action is fired, navigating to the anchor # on your site (which is the top).

Try:

$("#invio_scatola_on, #invio_scatola_off").click(function(event){
    $("#invio_scatola_off").toggle();
    $("#invio_scatola_on").toggle();
    event.preventDefault();
});

and see if that helps. More on event cancelling with jQuery here:

http://api.jquery.com/event.preventDefault/

Upvotes: 1

adeneo
adeneo

Reputation: 318352

You probably need to prevent the default action of whatever element you click:

$("#invio_scatola_on, #invio_scatola_off").on('click', function(e){
    e.preventDefault();
    $("#invio_scatola_off, #invio_scatola_on").toggle();
});

Upvotes: 3

Zuul
Zuul

Reputation: 16269

Based on the few information that you've provided, if the browser is scrolling to the top, it means that you need to prevent its default behavior.

Check to see if the browser is appending "something" to the current URL...

You can prevent that like this:

$("#invio_scatola_on, #invio_scatola_off").click(function(event){

  // prvent default behavior
  event.preventDefault();

  $("#invio_scatola_off").toggle();
  $("#invio_scatola_on").toggle();
});

See the jQuery event.preventDefault() for more information on how it works.

Upvotes: 1

Related Questions