I’m using a bit of javascript to fade in a couple of message bars at the top of my page – a bit like stackoverflow does 🙂
I have:
<div id='message' style="display: none;">
<span>Wow, that was quick! - below is a preview of your page.</span>
<a href="#" class="close-notify">X</a>
</div>
<div id='message' style="display: none;">
<span>Try posting something interesting</span>
<a href="#" class="close-notify">X</a>
</div>
CSS:
#message {height:30px;width:100%;z-index:105;text-align:center;color:white;padding:10px 0px 10px 0px;background-color:#8E1609;}
#message span {text-align: center;width: 95%;float:left;}
.close-notify {white-space: nowrap;float:right;margin-right:10px;color:#fff;text-decoration:none;border:2px #fff solid;padding-left:3px;padding-right:3px}
.close-notify a {color: #fff;}
and Javascript:
$(document).ready(function() {
$("#message").fadeIn("slow");
$("#message a.close-notify").click(function() {
$("#message").fadeOut("slow");
return false;
});
});
But unfortunately only the first message displays. How come? Surely the second one should show as well?
thanks
idattributes should be unique among all elements in the page. Change the HTML, CSS and JavaScript to useclass="message"instead ofid="message"and it will work fine.Technically what happens here is that jQuery sees the
#messageselector and tries to find the element usingdocument.getElementById(which is fastest). This function returns only one element, in this case the first one. So the second never has a chance to be processed.You also have a bug: As the code stands now, hitting the “close” link will make all messages disappear. You need to tweak the
clickhandler a bit to make it behave as expected.See all of this in action here.