zzxjoanw zzxjoanw - 6 months ago 14
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()
{
$('#bannerChoice').slideToggle(function()
{
if($('#bannerChoice').is(':visible'))
{
$('html').css({overflow:"hidden",height:"100%"});
}
else
{
$('html').css({overflow:"auto",height:"2171px"});
}
});
}

function toggleForm()
{
$('#search').slideToggle(350);
return false;
}


and

<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"
onClick="setBanner(1,event);"/>
<img src="/media/profile/images/bgs/bg2_thumb.png"
onClick="setBanner(2,event);"/>
<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"
onClick="bannerChoice()">
</span>
</form>
</div>

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


and

<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;"
value="Search">
</form>
</div>

Answer

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)
{
    e.preventDefault();
    $('#search').slideToggle(350);
}

And you need to add event to your call:

onclick='toggleForm(event)'

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.

Comments