zzxjoanw zzxjoanw - 2 years ago 97
jQuery Question

Jquery Slidetoggle: Why does it reload my page?

I'm having a strange issue with two slideToggles. The #bannerChoice slide works fine, but the #search slide, which should, when open, overlap #bannerChoice, never opens more than partway. Instead, it forces the page to reload.

Here's my code:

function bannerChoice()

function toggleForm()
return false;


<div id="bannerChoice">
<div id="bcText">Select a banner graphic:<br/></div>
<div id="bcImages">
<form action="#" method="post">
<input type="hidden" name="setBanner" id="setBanner" value="">
<img src="/media/profile/images/bgs/bg1_thumb.png"
<img src="/media/profile/images/bgs/bg2_thumb.png"
<img src="/media/profile/images/bgs/bg3_thumb.png"
onClick="setBanner(3,event)" />
<img src="/media/profile/images/bgs/bg4_thumb.png"
onClick="setBanner(4,event)" /><br/>
<span id="bcBttns">
<input type="submit" value="Submit" class="submit"
name="bttnSubmit" /><input type="button" value="Cancel"

<div id="bcBG">&nbsp;</div>


<span onClick="toggleForm()">
<a href="" style="display:inline-block; color:#bbb; padding:0 13px;
line-height:70px;">link text</a></span>
<div style="padding-left:13px; z-index:9004">
<form id="search" method="post" action="#">
<input type="text" name="name" value="Name" style="width:112px"/><br/>
<input type="text" name="city" value="City" style="width:112px" /><br/>
<input type="text" name="state" value="State" style="width:112px" /><br/>
<input type="text" name="zip" value="Zip" style="width:112px" /><br/>
<input type="button" class="submit" style="margin:0 13px 0 13px;"

Answer Source

The jQuery is not causing your page to refresh. When you click the link in your span, the page will go to url "", i.e. reloading your current page.

You need to add e.preventDefault() to your script to prevent the link from performing its default action (going to the link):

function toggleForm(e)

And you need to add event to your call:


bannerChoice() does not reload the page, because it is on a cancel button, which does not post as part of its default action.

As others have said here, inline Javascript is not a good idea. It makes code unreadable, difficult to debug, and prevents you from reusing code easily. There is no (good) reason to use inline Javascript with jQuery.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download