I want to have a box (a <div>) to display shortly after the page is loaded, for it to fade in and for a user to be able to close/hide the box if they wish. I have got most of the way there but after I close the box it reappears. I can’t help but think I shouldn’t have
style="display:block"
on the <div> but if I don’t it doesn’t fade in. My code is as follows:
You are on the right track.
I would recommend not using any inline styling (as you mentioned).
But, more importantly, I think you should reverse your logic.
In other words, create a class that HIDES the box (display: none;)
Apply that class to the box initially. In your onLoad/Timeout JS call the ‘showBox’ function which removes the class.
Then, you can use the ‘hideBox’ to apply that original class (which hides the box).
This all can be done [more] easily with JQuery. And you can animate it in addition!!
What is happening is that your click is resulting in the page loading up again.
You can prevent that from happening by disabling the default behaviour of that link. You can achieve that by returning false from the function, and in turn, returning the hidebox function in the onclick attribute.
You can also remove the display:none from your CSS and you won’t need the display:block in your HTML code.
===
There are better ways to achieve what you’re wanting to do here, that result in more flexible and easily maintainable code.
[list][]Keep your HTML and scripting code separate from each other
[]Load your scripts from the end of the body
[]Pass a function to setTimeout instead
[]Target the link instead of the image - and use cascading to reach the img tag
[]Attach events from the scripting code instead of using inline event attributes
[]Use class names for CSS selectors instead of ID tags
[/list]
We could spend all day going over details about the above tips, and you’re welcome to please ask for more info about any of them.
After the above improvements, you end up with the following:
It’s much better to use cursor:default to achieve what you’re wanting with the cursor.
#infobox {
...
cursor: default;
}
It’s not a good idea for scripting to replace the entire classname of an element either. Here are some functions that let you add and/or remove a certain name from the class instead.
Actually, the cursor:default doesn’t work. The problem occurs if there is something behind the box. I have uploaded my page to http://gandalf458.co.uk/infobox3.html so you can see. Thanks G