<script>
function showhide() {
document.getElementById('someimage').style.visibility="hidden";
}
</script>
At the moment I am able to hide the image, however then I have no way to show it again.
How can I hide and then be able to show an image when clicking a button using javascript?
Here's the button:
<body>
<input type="button" onclick="showhide()" />
</body>
Simply check what the current state is, and then act accordingly.
function showhide() {
var img = document.getElementById('someimage');
if (img.style.visibility === 'hidden') {
// Currently hidden, make it visible
img.style.visibility = "visible";
} else {
// Currently visible, make it hidden
img.style.visibility = "hidden";
}
}
And a quick note about jQuery to all those suggesting it.
For simple things like this, there is no need to include a big DOM manipulation library. If you are doing a lot of DOM manipulations like this in a more complex application, then jQuery starts to make more sense to include.
But it's also important to understand what jQuery is doing for you under the hood when you use it.
The wonders of jQuery - http://jsfiddle.net/PbG3t/
$(function() {
$('#button').click(function() {
$('#someimage').toggle();
});
});
If you are using jQuery, you can use the (.toggle) method which simplifies things a lot:
$('#someimage').toggle();
If you want to stick with a hand-crafted solution, I guess your code is actually missing the deciding bit that sets the element's visibility back to visible. Try:
<script>
function showhide() {
var element = document.getElementById('someimage');
element.style.visibility = element.style.visibility == 'visible'
? 'hidden'
: 'visible';
}
</script>
Cheers, Alex
Related
I want the visitor to be able to expand/collapse some sections, and am using:
<input onclick="return toggleDiv('xx')"
type="button"
class="button"
value="click here to expand/collapse"/>
and in the I have the function:
function toggleDiv(a){
var e=document.getElementById(a);
if(!e)return true;
if(e.style.display=="none"){
e.style.display="block"
} else {
e.style.display="none"
}
return true;
}
The first time a button is clicked it doesn't work, subsequent clicks (on any of the buttons) work OK.
There is related conversation here:
Button needs to be clicked twice to trigger function
but I don't understand the answer (too technical;-),
could someone help explain it please?
The initial style on your 'xx' div may be causing some trouble...
Explanation
Say you have a stylesheet rule configured to make your divs initially hidden. Something like:
div { display: none }
(...where of course the selector (div) will probably be a little bit less broad)
This would appear to work correctly, in that the page will load with all of your div elements hidden ("collapsed"). However, there's no actual value for the style.display property on the elements themselves - they're merely inheriting the value from the stylesheet. So in your code, the test you're using to check if the element is hidden:
if(e.style.display=="none"){
...will fail, incorrectly identifying the target as being visible, and causing the style.display property to be set to "none" (which has no visible effect, since the element had already been hidden by the stylesheet). Then the next time the button is clicked, the value you set the last time around will cause the text to succeed, and your routine will set style.display to "block".
The easy way to correct for this is to simply reverse your test and check for "block":
if(e.style.display=="block"){
e.style.display="none"
} else {
e.style.display="block"
}
...however, this will fall apart if you have some elements configured to be initially visible: you'll just run into the same problem in reverse, with the first button click failing to have any visible effect. For a more robust behavior, you'll need to test the style that's actually active on the element:
function getStyle(el, name)
{
// the way of the DOM
if ( document.defaultView && document.defaultView.getComputedStyle )
{
var style = document.defaultView.getComputedStyle(el, null);
if ( style )
return style[name];
}
// IE-specific
else if ( el.currentStyle )
return el.currentStyle[name];
return null;
}
function toggleDiv(a){
var e=document.getElementById(a);
if(!e)return true;
if(getStyle(e, "display") == "none"){
e.style.display="block"
} else {
e.style.display="none"
}
return true;
}
Here we use a helper function, getStyle(), to retrieve the active value in a cross-platform manner. See also: getComputedStyle(), currentStyle
more easy implémentation some how
var a=1;
function toggleDiv(xx){
var e=document.getElementById(xx);
if(a==1){
e.style.display="block";a=0;
} else {
e.style.display="none";
a=1;
}
}
To save all the extra Javascript code to get the style etc, a simple fix for this would be to add the hide CSS to the element itself.
<div class="yourclass" style="display:none;">content</div>
edit
I decided to explain my answer a little better. I'm assuming you didn't hide the div you wanted to toggle by default, so it was visible, however when calling e.style.display the result would not be none neither would it be block because the style hasn't been set yet.
Instead, you were retrieving an empty string which means the first time you clicked it, your else statement was firing; the div display was being set to none on first click, that way the next click would retrieve the value as none so of course would then change it to block.
The simple answer you're looking for is to add the display:none; to the inline style. This way, when you look at
if (x.style.display == 'none')
it will return true!
I know this is an old thread, but for the sake of being somewhat useful (for a change), you could always call the current display within the function. alternatively you could define on-load, but given the button might not be clicked, I would prefer to do via a addEventListener().
document.getElementById("someID1").addEventListener("click", hideOpen);
function hideOpen() {
var x = document.getElementById("someID2");
x.style.display = window.getComputedStyle(document.getElementById("someID2")).display;
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
Effectively you load the JS, then when an element is clicked (someID1), the function will define varible X, assign the current computed style.display and then test the if it's block or none.
Something like this might work for you. But put it in the head of the document. the window onload function is important because the DOM needs to be loaded before you can mess around with the input field
<input id="divOpener" rel="xx" type="button" class="button" value="click here to expand/collapse"/>
and this
window.onload = function(){
// get input field from html
var myInput = document.getElementById('divOpener');
// add onclick handler
myInput.onclick = function(){
// if you really need to say which div in the document body, you can
// add it to the rel or ref etc. attributes then get the value with
// get attribute
var myDiv = document.getElementById(this.getAttribute('rel'));
if(!myDiv) return;
if(myDiv.style.display=="none"){
myDiv.style.display="block";
} else {
myDiv.style.display="none";
}
}
}
Shog9's answer saved me from an evening's frustration. Thanks.
However there's a much simpler solution than the one he presents. The secret is simply to switch around the order of the conditional. i.e.
if(e.style.display == "block"){
e.style.display="none"
} else {
e.style.display="block"
}
The insight here is simply that the condition can fail for two different reasons: if the value is unobtainable it will do the right thing anyway.
I'm writing javascript which will change the color of an element when the mouse hovers over it. I know perfectly how to do this using jQuery, but this time around I have to do it using either pure JS or Prototype.
Why doesn't this work:
<div id="boundary1"></div>
document.getElementById("boundary1").onmouseover(function() {
alert("test");
})
firebug returns:
TypeError: document.getElementById(...).onmouseover is not a function
Your syntax is wrong, you may be thinking a little too 'jQuery', try this:
var boundary = document.getElementById('boundary');
var mouseOverFunction = function () {
// this.style.color = '#000'; // your colour change
};
boundary.onmouseover = mouseOverFunction;
I've separated the logic to make the development and logic clearer, it makes your functions reusable too.
The Prototype way to do this would be this:
$('elementId').observe('mouseenter', function(evt){
this.setStyle('background-color: yellow');
}).observe('mouseleave', function(evt){
this.setStyle('background-color: inherit');
});
But as others have already pointed out, the real way to do this is with CSS. The only reason I could imagine needing to do it in JS is if you have to support IE <= 8, which doesn't like to do the :hover pseudo-class on anything except the A tag.
Try:
document.getElementById("boundary1").onmouseover = function() {
alert("test");
}
More Info.
Try this code
<td onMouseOver="this.bgColor='#00CC00'" onMouseOut="this.bgColor='#009900'" bgColor=#009900>
Click Here</TD>
You can do it using CSS
<style>
.changecolour:hover
{
background-color:yellow;
}
</style>
Now for the text you want to change color
<span class ="changecolour">Color changes when mouse comes here.</span>
Reference : http://www.w3schools.com/cssref/sel_hover.asp
I'm building a website which has tooltips to give advice on what to do which display after a few seconds of inactivity. The thing is, there's certain circumstances when I don't want them to show up.
The website has 'pop-ups' (just div tags on which the z-index is changed). When these tags are 'in view' I don't want the tool tips. Is there anything I can do to the code to check if a div is at a certain level, or perhaps insert a command to NOT run the tooltip code...
My tooltip script is
<!-- JavaScript function to show/hide prompts after innactivity-->
<script type="text/javascript">
$(document).ready(function(){
var interval = 1;
setInterval(function(){
if(interval == 9){
$("div.container_prompts_timeout").show();
interval = 1;
}
interval = interval+1;
console.log(interval);
},1000);
$(document).bind('mousemove keypress', function() {
$("div.container_prompts_timeout").hide();
interval = 1;
});
});
</script>
And the code I use to change z-index is:
<!--Code to change z-index of background divs-->
<script type="text/javascript">
function changeZIndex(i,id) {
document.getElementById(id).style.zIndex=i;
}
</script>
Many thanks
Why not to use display property of your divs to hide and show them.
And you can check the state of it.
Something like
var my_div = getElementById("my_div");// or use your jQuery if you wish
function show() {
my_div.style.display = "block";
}
function hide() {
my_div.style.display = "none";
}
function is_shown() {
if (my_div.style.display == "none") return 0;
return 1; // use booleans if you wish, I prefer old school :)
}
you could:
check if the popups are "visible" before showing the tooltips, or
cancel the interval when they become visible and restart it when they are hidden
personally, I wouldn't use the z-index to show or hide things. I would set their actual display style property to 'none' to hide them. this would allow you to check this property before showing the tooltips, because checking the z-index of the element might be a little cumbersome.
I'm very frustrated right now... and making lots of mistakes. Sorry about that
I've been trying to unhide a specific div based on search results
If no search was made the div should not appear, and this is easy with css, but once the search is done I have to change the style to 'block'.
Since I'm using the google custom search javascript its too hard to replace the button for another similar button that triggers my javascript function.
I also couldn't figure out how to replace the "resultDiv" into some more complex path
I already done this javascript function to hide a div based on the result div...
css div style is at #main.section .widget.HTML
function check()
{
if (document.getElementById('resultDiv')) {
if ($('.gsc-expansionArea').is(":empty")) {
document.getElementById('resultDiv').style.display = 'none';
}
else {
document.getElementById('resultDiv').style.display = 'block';
}
}
}
I think there might be 2 possible solutions. First is to load the script
<body onLoad="check();">
but doesn't seems to work.
Second would be check URL for ?q= meaning a search was done, but I don't know how to get these parameters from URL.
Please assist me. Thank you
well, since you've tagged jquery:
$(window).load(function(){
check();
})
and your function check() could be more like
function check() {
if ($('#resultDiv').length) {
if ($('.gsc-expansionArea').is(":empty")) {
$('#resultDiv').css({'display': 'none'})
}
else {
$('#resultDiv').css({'display': 'block'})
}
}
}
--
Second would be check URL for ?q= meaning a search was done, but I
don't know how to get these parameters from URL.
use location.search
Location search Property
MDN window.location
Replace
<body onLoad="javascript:check();">
with
<body onLoad="check();">
You can use
$(document).ready(function()
{
check();
}
to load the function when the page loads. You can also simplify your function with jQuery:
function check()
{
var isEmpty= $('.gsc-expansionArea').is(":empty");
$('#resultDiv').toggle(isEmpty);
}
The documentation for toggle is here.
I want the visitor to be able to expand/collapse some sections, and am using:
<input onclick="return toggleDiv('xx')"
type="button"
class="button"
value="click here to expand/collapse"/>
and in the I have the function:
function toggleDiv(a){
var e=document.getElementById(a);
if(!e)return true;
if(e.style.display=="none"){
e.style.display="block"
} else {
e.style.display="none"
}
return true;
}
The first time a button is clicked it doesn't work, subsequent clicks (on any of the buttons) work OK.
There is related conversation here:
Button needs to be clicked twice to trigger function
but I don't understand the answer (too technical;-),
could someone help explain it please?
The initial style on your 'xx' div may be causing some trouble...
Explanation
Say you have a stylesheet rule configured to make your divs initially hidden. Something like:
div { display: none }
(...where of course the selector (div) will probably be a little bit less broad)
This would appear to work correctly, in that the page will load with all of your div elements hidden ("collapsed"). However, there's no actual value for the style.display property on the elements themselves - they're merely inheriting the value from the stylesheet. So in your code, the test you're using to check if the element is hidden:
if(e.style.display=="none"){
...will fail, incorrectly identifying the target as being visible, and causing the style.display property to be set to "none" (which has no visible effect, since the element had already been hidden by the stylesheet). Then the next time the button is clicked, the value you set the last time around will cause the text to succeed, and your routine will set style.display to "block".
The easy way to correct for this is to simply reverse your test and check for "block":
if(e.style.display=="block"){
e.style.display="none"
} else {
e.style.display="block"
}
...however, this will fall apart if you have some elements configured to be initially visible: you'll just run into the same problem in reverse, with the first button click failing to have any visible effect. For a more robust behavior, you'll need to test the style that's actually active on the element:
function getStyle(el, name)
{
// the way of the DOM
if ( document.defaultView && document.defaultView.getComputedStyle )
{
var style = document.defaultView.getComputedStyle(el, null);
if ( style )
return style[name];
}
// IE-specific
else if ( el.currentStyle )
return el.currentStyle[name];
return null;
}
function toggleDiv(a){
var e=document.getElementById(a);
if(!e)return true;
if(getStyle(e, "display") == "none"){
e.style.display="block"
} else {
e.style.display="none"
}
return true;
}
Here we use a helper function, getStyle(), to retrieve the active value in a cross-platform manner. See also: getComputedStyle(), currentStyle
more easy implémentation some how
var a=1;
function toggleDiv(xx){
var e=document.getElementById(xx);
if(a==1){
e.style.display="block";a=0;
} else {
e.style.display="none";
a=1;
}
}
To save all the extra Javascript code to get the style etc, a simple fix for this would be to add the hide CSS to the element itself.
<div class="yourclass" style="display:none;">content</div>
edit
I decided to explain my answer a little better. I'm assuming you didn't hide the div you wanted to toggle by default, so it was visible, however when calling e.style.display the result would not be none neither would it be block because the style hasn't been set yet.
Instead, you were retrieving an empty string which means the first time you clicked it, your else statement was firing; the div display was being set to none on first click, that way the next click would retrieve the value as none so of course would then change it to block.
The simple answer you're looking for is to add the display:none; to the inline style. This way, when you look at
if (x.style.display == 'none')
it will return true!
I know this is an old thread, but for the sake of being somewhat useful (for a change), you could always call the current display within the function. alternatively you could define on-load, but given the button might not be clicked, I would prefer to do via a addEventListener().
document.getElementById("someID1").addEventListener("click", hideOpen);
function hideOpen() {
var x = document.getElementById("someID2");
x.style.display = window.getComputedStyle(document.getElementById("someID2")).display;
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
Effectively you load the JS, then when an element is clicked (someID1), the function will define varible X, assign the current computed style.display and then test the if it's block or none.
Something like this might work for you. But put it in the head of the document. the window onload function is important because the DOM needs to be loaded before you can mess around with the input field
<input id="divOpener" rel="xx" type="button" class="button" value="click here to expand/collapse"/>
and this
window.onload = function(){
// get input field from html
var myInput = document.getElementById('divOpener');
// add onclick handler
myInput.onclick = function(){
// if you really need to say which div in the document body, you can
// add it to the rel or ref etc. attributes then get the value with
// get attribute
var myDiv = document.getElementById(this.getAttribute('rel'));
if(!myDiv) return;
if(myDiv.style.display=="none"){
myDiv.style.display="block";
} else {
myDiv.style.display="none";
}
}
}
Shog9's answer saved me from an evening's frustration. Thanks.
However there's a much simpler solution than the one he presents. The secret is simply to switch around the order of the conditional. i.e.
if(e.style.display == "block"){
e.style.display="none"
} else {
e.style.display="block"
}
The insight here is simply that the condition can fail for two different reasons: if the value is unobtainable it will do the right thing anyway.