开发者

JavaScript CSS change is only for a second?

I have some JavaScript that is supposed to change the display property from none to block. What happens is it f开发者_JS百科lashes on the screen then goes away in half a second.

<input type="image" src="images/joinButton.jpg" name="join" value="Join" onclick="check(this.form)" />

function check(form){
        var errorFields = document.getElementById('errorFields');
        errorFields.style.display = 'block';
}


Changing the style display via javascript should stick unless something else is happening after it that changes it back. For example, try this code in a new html file:

<html>
<head>
<script type="text/javascript">
function check(){
    var errorFields = document.getElementById('errorFields');
    errorFields.style.display = 'block';
}
</script>
</head>
<body>
<div id="errorFields" style="border: 1px solid red; height: 300px; width: 300px; display: none;"></div>
<input type="button" name="join" value="Join" onclick="check()" />
</body>
</html>

It'll make a red box appear after you click the button. What's likely happening is there's another event tied to your button click that's happening after your check() function, so it displays, and then hides immediately after.


This is what is probably happening:

  1. Image clicked
  2. Styles changed
  3. Form submitted
  4. Page reloaded with original styles

You need to return false from the event handler to cancel the normal operation of the image map if you don't want the form to submit.

onclick="return check(this.form)"


function check(form){
    var errorFields = document.getElementById('errorFields');
    errorFields.style.display = 'block';
    return false;
}

You would probably be better off using unobtrusive JS and replacing the image map's click event with the form's submit event though.


The reason the flashing occurs is because you most likely have a conflict between your CSS and your JavaScript (or another JavaScript function being called that is hiding the content).

Also, the style.display property may not work properly in all browsers. I suggest the following:

errorFields.style.display = "block";
errorFields.setAttribute("style","display:block");

I also suggest using a tool like Firebug to inspect the elements and see what other CSS is being applied to your element so you can detect the conflict.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜