Image will not switch between hidden and show - javascript

I cannot get an image to switch back and forth between 'hidden' and 'show'
I'm using ideas from
How to create a hidden <img> in JavaScript?
I have two different buttons, trying one using html and the other to use javascript - If I comment out one line, the light bulb photo is displayed
//document.getElementById("light").style.visibility = "hidden";
That line of code is in my 'init' function
If I do not comment the line, the light stays 'hidden', no matter which of the buttons I click
I don't see any errors in the Web Console Log in Safari
<!DOCTYPE html>
<html>
<body>
<h1>Switch on the Light</h1>
<img id="light" src="WebVuCoolOldBulb-2.jpg" style="width:100px" >
<button type = button
onclick="document.getElementById('light').src.show ='WebVuCoolOldBulb-2.jpg'" >Switch On the Light
</button>
<input type="button" id="onButton" value="ON" />
</body>
<script>
//document.images['light'].style.visibility = hidden;
function init() {
//document.getElementById("light").style.visibility = "hidden";
var onButton = document.getElementById("onButton");
onButton.onclick = function() {
demoVisibility() ;
}
}
function demoVisibility() {
document.getElementById("light").style.visibility = "show";
}
document.addEventListener('readystatechange', function() {
// Seems like a GOOD PRACTICE - keeps me from getting type error I was getting
// https://stackoverflow.com/questions/14207922/javascript-error-null-is-not-an-object
if (document.readyState === "complete") {
init();
}
});
</script>
</html>

The visibility style property has values of visible and hidden.
There is no show value.
function init() {
document.getElementById("light").style.visibility = "hidden";
var onButton = document.getElementById("onButton");
onButton.onclick = function() {
demoVisibility();
}
}
function demoVisibility() {
document.getElementById("light").style.visibility = "visible";
}

Related

how to show image on click, and hide it again when clicking again

I want to when I click on a sentence or a button an image appears, and when I click it again it disappears. but my code doesn't seem to work using JS and HTML.
let pic = document.getElementById("hiddenclickimg");
let word = document.getElementById("hiddenclick");
function showPic(){
pic.hidden = 'false' ;
word.style.color = 'red';
word.style.backgroundColor = 'blue';
}
word.onclick = showPic;
<h3 id="Work">Work Experience</h3>
<div class="work">
<ul>
<li>
<img
src="./Images/Alex Sydney.jpg"
alt="alex sydney"
id="hiddenclickimg"
hidden="true"
/>
<button id="hiddenclick">Alex Sydney Hospital</button>
</li>
</ul>
</div>
<script src="./main.js"></script>
You can use the onclick of a button and toggle a class that hides the image when it has that class.
HTML:
<button onclick="imageClick()">Toggle Image</button>
CSS:
.hidden {
opacity: 0;
}
Javascript:
const image = document.getElementById('hiddenclickimg');
const imageClick = () => {
image.classList.toggle('hidden');
}
There are different CSS properties you could use to hide the image, but opacity is a good basic one.
You don't need to set 2 ids to do the trick using css property display none.
For example you want to hide that image:
<img id="dog_image" src="dog.png" alt="Rex the Labradoodle" >
function hideDog() {
const dog = document.getElementById("dog_image");
if (dog.style.display === "none") {
dog.style.display = "block";
} else {
dog.style.display = "none";
}
}
And then just set the button:
<button onclick="hideDog()">Hide/Show my dog</button>
you can use flag to change state of the image like following
let imagehidden =false
let pic = document.getElementById('hiddenclickimg');
let word = document.getElementById('hiddenclick');
function showPic(){
if(imagehidden){
pic.hidden = false ;
word.style.color = 'red';
word.style.backgroundColor = 'blue';
imagehidden=false
}
else{
pic.hidden =true;
imagehidden=true
}
}

JavaScript addEventListener 'click''

I struggling with very basic thing
I am trying to make this side-nav appear and disappear with JavaScript. The code below only activates the nav bar but doesn't deactivate it. Tried all options but I don't know how to call function to close nav-bar.
Thank you
HTML
<div id="mySidenav" class="sidenav">
×
About
Services
Clients
Contact
</div>
<!-- Use any element to open the sidenav -->
<span id="MyElement">×</span>
JS
<script type="text/javascript">
function changeClass() {
document.getElementById("mySidenav").style.width = "250px";
}
window.onload = function() {
document.getElementById("MyElement").addEventListener('click',changeClass);
}
</script>
</body>
</html>
You can't have to objects with the same ID (use name instead?)
You have a typo in else if with comparator mark and another in the next line with assingment mark.
Since in menu.style.width == "-250px" you would be assigning value to -250 (menu.style.width == "0px) would never pass and it would keep assigning value -250 whenever someone clicks the button, but that fails, because you have a typo in your assingment mark.
Width cannot be negative
Is let compatable with your browser?
Have you considered using display:none and display:block (or whatever display you have)?
function toggleMenu() {
var menu = document.getElementById('mySidenav');
if (menu.style.display == "none")
menu.style.display = "inline-block"; //block
else
menu.style.display = "none";
}
window.onload = function() {
document.getElementById("MyElement").onclick = toggleMenu;
}
your else statement section seems to have the comparator (==) and assignment (=) the wrong way around :
} else if (menu.style.width = "250px") {
menu.style.width == "-250px";
}
looks like it should be
} else if (menu.style.width == "250px") {
//setting a negative width will immediately break the toggle logic.
//just set it to 0px.
menu.style.width = "0px";
}
Full example :
function changeClass() {
var sidenavElement = document.getElementById("mySidenav");
if(sidenavElement.style.width == "0px")
{
sidenavElement.style.width = "250px";
}
else
{
sidenavElement.style.width = "0px";
}
}
window.onload = function() {
document.getElementById("MyElement").addEventListener('click',changeClass);
}
#mySidenav
{
overflow:hidden;
height:100px;
background:green;
}
<div id="mySidenav" style="width:0px">
HELLO I AM SIDENAV
</div>
<button id="MyElement">toggle it</button>
There is many problem in your code, you have 2 elements inside your DOM with same ID as mentioned by Marek Maszay.
Your else statement should use == in condition and = for assignation.
Last thing, you should not use width property to display or not an element there is a display property in css
<html>
<body>
<div id="mySidenav" class="sidenav">
<span class="closebtn" id="MyElement">×</span>
<span id="menu">
About
Services
Clients
Contact
</span>
</div>
<!-- Use any element to open the sidenav -->
<span id="MyElement2">×</span>
<script type="text/javascript">
function toggleMenu() {
let menu = document.getElementById('menu');
if (menu.style.display == "") {
menu.style.display = "none";
} else if (menu.style.display == "none") {
menu.style.display = "";
}
}
window.onload = function() {
document.getElementById("MyElement").addEventListener('click',toggleMenu);
}
</script>
...
</body>
</html>
When display value is "", it take the default display value of an element, when its value is none the element is not displayed.
Here is your code modified.
EDIT
For some reason changing width to 0px doesn't hide the element. Element change from line to column, it seem that the browser try to fill element with content and put at least one word per line.
Seem like other people on web are having same problem.

Spinning circle on click

I have a code where onclick a word on left side of the page, it shows some text on right hand side of page. Here's the jsfiddle of working code.
Now, my problem is I want to display spinning circle on page on every onclick and then show text on the right hand side of the page. My code for spinning circle is:
HTML:
<div id="loading">
<img src="http://jimpunk.net/Loading/wp-content/uploads/loading1.gif"/>
</div>
JavaScript:
function hideLoading() {
document.getElementById("loading").style.display = 'block';
}
function showLoading() {
document.getElementById("loading").style.visibility = 'visible';
}
CSS:
#loading {
display: none;
}
Now, I don't know how to place them in my working code to get the desired result. Anybody knows the correct way of doing it?
Desired result: onclick "abc" on left hand side, spinning circle should be displayed for 1 sec and then "I should be printed on left side" should be displayed. Again on clicking "mno", first spinning circle should be shown for 1 sec and then text "I should be printed on left side" will be displayed. The fiddle has working version of onclick.
You should use a single handler function on each element that will both hide and show the loading gif. Also, it's a good idea not to use getElementById on every call, so save it in a variable:
<div id="container">
<div id="header">
<h1>Main Title of Web Page</h1>
Here I am trying to split the webpage into two columns and display text.</div>
<div id="one">
<div id="loading">
<img src="http://support.snapfish.com/euf/assets/images/answer_images/SpinningWheel.gif" />
</div>
<div id="message"></div>
</div>
<div id="two"> <b>This is test one<br /></b>
<b>This is test two<br /></b>
</div>
Javascript:
var elements = {};
function loadSpanContent() {
elements.loading.style.display = 'block'; // Show loading gif
spanContent = this.innerHTML
setTimeout(function () {
elements.message.innerHTML = "I should be printed on left side - " + spanContent;
elements.loading.style.display = 'none'; // Hide loading gif
alert("onclick Event detected! " + spanContent);
}, 1000);
}
window.onload = function mydisplayArray() {
var array = ['abc', 'xyz', 'mno'];
elements.loading = document.getElementById("loading");
elements.one = document.getElementById("one");
elements.message = document.getElementById("message");
for (i = 0; i < array.length; i++) {
var span = document.createElement('span');
span.innerHTML = array[i];
span.onclick = loadSpanContent;
one.appendChild(span);
}
};
Here is a fiddle: http://jsfiddle.net/nBaCJ/1/
I'm still confused by what you actually want here, but if you want to have the loading message disappear after one second, you should use setTimeout. Something like this:
function showAlert() {
showLoading();
setTimeout(hideLoading,1000);
//Hide loading circle
var myString = "I should be printed on left side";
document.getElementById("two").innerHTML = myString;
}
But you also need to fix your "showLoading" and "hideLoading". Something like this:
function hideLoading() {
document.getElementById("loading").style.display = 'none';
}
function showLoading() {
document.getElementById("loading").style.display = 'block';
}
http://jsfiddle.net/7uxHC/9/
BTW: if you want your loading gif to appear over your content, then set its position:absolute in css, but note that you gif has a white, rather than transparent background so it will obscure your content.
Your request isn't clear.
But first, you should fix these 2 functions:
function hideLoading() {
document.getElementById("loading").style.display = 'none';
}
function showLoading() {
document.getElementById("loading").style.display = 'block';
}

Change image in button on click

I've got a button with an image inside that I want to swap when clicked. I got that part working, but now I also want it to change back to the original image when clicked again.
The code I'm using:
<button onClick="action();">click me<img src="images/image1.png" width="16px" id="ImageButton1"></button>
And the Javascript:
function action() {
swapImage('images/image2.png');
};
var swapImage = function(src) {
document.getElementById("ImageButton1").src = src;
}
Thanks in advance!
While you could use a global variable, you don't need to. When you use setAttribute/getAttribute, you add something that appears as an attrib in the HTML. You also need to be aware that adding a global simply adds the variable to the window or the navigator or the document object (I don't remember which).
You can also add it to the object itself (i.e as a variable that isn't visible if the html is viewed, but is visible if you view the html element as an object in the debugger and look at it's properties.)
Here's two alternatives. 1 stores the alternative image in a way that will cause it to visible in the html, the other doesn't.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', mInit, false);
function mInit()
{
var tgt = byId('ImageButton1');
tgt.secondSource = 'images/image2.png';
}
function byId(e){return document.getElementById(e);}
function action()
{
var tgt = byId('ImageButton1');
var tmp = tgt.src;
tgt.src = tgt.secondSource;
tgt.secondSource = tmp;
};
function action2()
{
var tgt = byId('imgBtn1');
var tmp = tgt.src;
tgt.src = tgt.getAttribute('src2');
tgt.setAttribute('src2', tmp);
}
</script>
<style>
</style>
</head>
<body>
<button onClick="action();">click me<img src="images/image1.png" width="16px" id="ImageButton1"></button>
<br>
<button onClick="action2();">click me<img id='imgBtn1' src="images/image1.png" src2='images/image2.png' width="16px"></button>
</body>
</html>
You need to store the old value in a global variable.
For example:
var globalVarPreviousImgSrc;
var swapImage = function(src)
{
var imgBut = document.getElementById("ImageButton1");
globalVarPreviousImgSrc = imgBut.src;
imgBut.src = src;
}
Then in the action method you can check if it was equal to the old value
function action()
{
if(globalVarPreviousImgSrc != 'images/image2.png')
{
swapImage('images/image2.png');
}else{
swapImage(globalVarPreviousImgSrc);
}
}
It's not a good idea to use global variables in javascripts use a closure or object literal. You can do something like using a closure
(function(){
var clickCounter = 0;
var imgSrc1 = "src to first image";
var imgSrc2 = "src to second image"
functions swapImage (src)
{
var imgBut = document.getElementById("ImageButton1");
imgBut.src = src;
}
function action()
{
if(clickCounter === 1)
{
swapImage(imgSrc1);
--clickCounter;
}else{
swapImage(imgSrc2);
++clickCounter;
}
}
})();
(I haven't run this code though)
This nice w3documentation gives you best practices.
Check this a working example just copy paste and run-
HTML
<button onClick="action();">click me<img src="http://dummyimage.com/200x200/000000/fff.gif&text=Image+1" width="200px" id="ImageButton1"></button>
JAVASCRIPT
<script>
function action()
{
if(document.getElementById("ImageButton1").src == 'http://dummyimage.com/200x200/000000/fff.gif&text=Image+1' )
document.getElementById("ImageButton1").src = 'http://dummyimage.com/200x200/dec4ce/fff.gif&text=Image+2';
else
document.getElementById("ImageButton1").src = 'http://dummyimage.com/200x200/000000/fff.gif&text=Image+1';
}
</script>
Check this working example - http://jsfiddle.net/QVRUG/4/

Image slideshow

I am using javascript to slideshow images.Images are loaded only when the user clicks the next button i.e there is no preloading before the slideshow begins. With every image there is a supporting description which is loaded by the same javascript from an array which is stored in the javascript file. The effect of this is such that the description on next image is shown even before the image is displayed. Please suggest me some method so that i can delay displaying the desprition until the image is loaded. Also a loading symbol could be of great help. Please let me know how to do that. Thanks.
You will have to show some code and be more specific if you want more specific answers but in the meanwhile, I think this tutorial could help you out:
JavaScript Timers with setTimeout and setInterval
You need to add an event listener for the image onload event and display your text in that event handler. Unfortunately, as with everything else, not every browser works the same way in this respect. If you google image onload you will find some good suggestions.
Show that image in a dynamically added iframe and add an onload listener to that iframe to show the description only when it loads.
Here's an example:
<script>
var i;
var ifm;
var spinner;
function popupIframeWithImageInit(id, parent, initImageNumber) {
ifm = document.getElementById(id);
i = initImageNumber;
if(ifm === null) {
ifm = document.createElement('iframe');
}
if(!spinner) {
spinner = document.getElementById('spinner');
}
ifm.setAttribute('src', google_logos[i]);
ifm.setAttribute('id', id);
ifm.setAttribute('name', id);
ifm.setAttribute('height', document.body.clientHeight - 50);
ifm.setAttribute('width', '840');//width is fixed because the image is assumed to be fixed size 800
ifm.setAttribute('scrolling', 'yes');
ifm.setAttribute('frameborder', '0');
ifm.style.display= 'none';
ifm.onload = function() {
document.getElementById("description").innerHTML = pic_description[i];
ifm.style.display= '';
spinner.style.display = 'none';
};
document.getElementById(parent).appendChild(ifm);
spinner.style.display = '';
}
function next() {
ifm.src = google_logos[++i];
spinner.style.display = '';
ifm.style.display= 'none';
}
function prev() {
ifm.src = google_logos[--i];
spinner.style.display = '';
ifm.style.display= 'none';
}
function dismissPopupIframeWithImage(parentId, ifmId) {
document.getElementById(parentId).removeChild(document.getElementById(ifmId));
spinner.style.display = 'none';
ifm.style.display= 'none';
return false;
}
//use large images to see the spinner
google_logos = ['http://sharevm.files.wordpress.com/2010/03/googlevsmicrosoft300dpi.jpg',
'http://hermalditaness.files.wordpress.com/2010/01/2.jpg',
'http://tuescape.files.wordpress.com/2008/10/tous20les20logos20google20par20aysoon.jpg',
'http://isopixel.net/wp-content/uploads/2007/02/logos-superbowl.gif'];
pic_description = ['http://sharevm.files.wordpress.com/2010/03/googlevsmicrosoft300dpi.jpg',
'http://hermalditaness.files.wordpress.com/2010/01/2.jpg',
'http://tuescape.files.wordpress.com/2008/10/tous20les20logos20google20par20aysoon.jpg',
'http://isopixel.net/wp-content/uploads/2007/02/logos-superbowl.gif'];
</script>
<img id="spinner" src="http://publish.gawker.com/assets/ged/img/spinner_16.gif" style="position:absolute; left:100px; top:150px; display:none;"/>
<div style="" id="panel"></div>
<div style="" id="description"></div>
<div >
<button onclick="popupIframeWithImageInit('imagePopup', 'panel', 1);">Open</button>
<button onclick="prev();"><-- Prev</button>
<button onclick="next();">Next --></button>
<button onclick="dismissPopupIframeWithImage('panel', 'imagePopup');">Close</button>
</div

Categories