Javascript - hide div box - having trouble!

Associate
Joined
3 Nov 2005
Posts
611
These are a few extracts from a page I am working on. Any obvious problems?

Code:
<script type="text/javascript">
function close(id)
{
document.getElementById('id').style.display = 'none';
}
</script>

<div id="maker_prompt">Not sure what to have? Try out our meal maker!
<div id="maker_close">
<a href="#" onclick="close('maker_prompt')">x</a>
</div>

IE9 and Firefox refuse to close the maker_prompt div...
 
By quoting 'id' you're sending in a literal with the string value 'id', and not your id argument.

Remove the quotes and you're good.

Thanks Goof! I'll try it later after work but I'm sure that will do the business. Fairly new to this Javascript lark as is clearly obvious ;)
 
Check out jQuery - it makes stuff like this trivial. I'd also apply a CSS class to the div, and not a style directly.

Something like

$('#maker_close').addClass('hidden');
 
I always have a class

.hidden
{
display:none;
visibility:hidden;
}

for DOM elements I don't want to show, and I just prefer applying this as it keeps things consistent.

It also nicely separates the DOM styling - I'm of the view that layout and styles should be done using CSS (i.e. no inline styles).

.hide() does give you the benefit of giving the animation a speed though.
 
Hmmm, think I might be being stupid again as it isn't working...

Code:
<script type="text/javascript">
function close(id)
{
document.getElementById(id).style.display = 'none';
}
</script>


<div id="maker_prompt">Not sure what to have? Try out our meal maker!
<div id="maker_close">
<a href="#" onclick="close(maker_prompt)">x</a>
</div>

Good option there lokkers. Might have to look into that as well. Note - I've tried this with quotes in the close argument around maker_prompt and without.
 
You're missing a closing </div> after maker_prompt - that's not going to help.

try this instead:

Code:
<script type="text/javascript">
    function close(id) {
        document.getElementById(id).style.display = 'none';
    }
</script>

<div id="maker_prompt">Not sure what to have? Try out our meal maker!</div>
<div id="maker_close">
<a href="javascript:close('maker_prompt');">x</a>
</div>

Sticking alert("my_message") everywhere is enormously useful when trying to debug javascript.
 
Lokkers - it required the 'javascript:' bit as you suggested to work correctly but work it did. Any reason why I needed that part? I thought it may just reference the function in the head without that? Examples I look at don't appear to need it?
 
Lokkers - it required the 'javascript:' bit

Yep, that's why I wrote it :p

I always presumed it has something to do with the default action of an anchor. Putting javascript: tells it to execute the contents of the href, not to try and browse to it. Sounds plausible.

Some info here, although I've only had time to skim it: stackoverflow.com
 
Back
Top Bottom