Javascript onclick function triggers from the second time i click but not the first - javascript

I have this two images that trigger the same function. What the function does is showing/hiding one of the images and then i added some extra code to show/hide a menu, that i haven´t included.
function menu() {
var b = document.getElementById("burger");
var c = document.getElementById("close");
if (b.style.display === "block") {
b.style.display = "none";
c.style.display = "block";
} else {
b.style.display = "block";
c.style.display = "none";
}
}
<img src="img/burger-white.png" id="burger" onclick="menu()" alt="img1">
<img src="img/close-white.png" id="close" onclick="menu()" alt="img2">
Everything works as intended, except for the first time i click on the image, when it does nothing.

It looks like the display for burger is not initially set to block. Try loading the page and inspect it with chrome. There you should see, when the page is loaded, if it initially have the expected css style.
A workaround, would be to add a function that will set the display of the element with id #burger to "block", if the window size is less that a 1100px.
function setDisplay() {
var width = window.innerWidth;
var b = document.getElementById("burger");
if(width <= 1100) {
b.style.display = "block";
}
}

Related

Why does it takes to click to apply my function? [duplicate]

This question already has answers here:
Why my show hide button needs double-click on first time
(3 answers)
Closed 1 year ago.
I'm trying to write a code that when you click the button it shows and when pressed again it hides images. I made that images display to none and I want it to change to block when pressed the button (so it shows the images).
It works, but only when you click twice.
What should I do to activate it on one click?
HTML :
<button id="categoryBtn" onclick="insta()">instagram users</button>
javascript :
function insta() {
var a = document.getElementById("instaBalas");
if (a.style.display == "none") {
a.style.display = "block";
} else {
a.style.display = "none";
}
}
Because when you click first time the display is empty string. So its then set to 'none' and works normally after. You can use getComputedStyle
const img = document.getElementById("instaBalas")
function insta() {
var a = window.getComputedStyle(img);
if (a.display == "none") {
img.style.display = "block";
} else {
img.style.display = "none";
}
}
<button id="categoryBtn" onclick="insta()">instagram users</button><br>
<img alt="Imgage" id="instaBalas">
Another way I would suggest to have a class and use classList.toggle()
const img = document.getElementById("instaBalas")
function insta() {
img.classList.toggle('hidden')
}
.hidden{
display:none;
}
<button id="categoryBtn" onclick="insta()">instagram users</button><br>
<img alt="Imgage" id="instaBalas">
The style object on an element doesn't reflect its current styling, it reflects the styles set directly on it. So e.style.display == "none" is false initially.
If you want to go that route, use getComputedStyle, which returns an object with the "computed"¹ style for the element, taking CSS into account:
function insta() {
var a = document.getElementById("instaBalas");
if (getComputedStyle(a).display == "none") {
// ---^^^^^^^^^^^^^^^^^^^
a.style.display = "block";
} else {
a.style.display = "none";
}
}
function insta() {
var a = document.getElementById("instaBalas");
if (getComputedStyle(a).display == "none") {
a.style.display = "block";
} else {
a.style.display = "none";
}
}
<button id="categoryBtn" onclick="insta()">instagram users</button>
<div id="instaBalas">instaBalas</div>
BUT, it would be better to define a class to hide the element, and then use toggle on the element's classList:
function insta() {
document.getElementById("instaBalas").classList.toggle("hidden");
}
Live Example:
function insta() {
document.getElementById("instaBalas").classList.toggle("hidden");
}
.hidden {
display: none;
}
<button id="categoryBtn" onclick="insta()">instagram users</button>
<div id="instaBalas">instaBalas</div>
All major browsers have classList, and it can be polyfilled for obsolete browsers.
¹ It's not really the computed property value, it's the resolved or used property value, details here.

expandable list - change images displayed when expanded \ closed

I have a series of expandable drop-down tabs using the ToggleList javascript function below. When the tab is closed I would like to display expand.png and when it's open I would like to display close.png. Right now Any help would be appreciated.
The code below expands\minimizes the dropdown tabs, but is not switching the png files.
Full javascript + html:
<script type="text/javascript">
function ToggleList(IDS) {
HideRange('ulist','div',IDS); // not required unless using 'HideRange()' below
var CState = document.getElementById(IDS);
if (CState.style.display != "block") { CState.style.display = "block"; }
else { CState.style.display = "none"; }
// get a reference to the image contained in the <a> that was just clicked
var img = this.getElementsByTagName('img')[0];
// switch the graphic, if it's expand set it to collapse, otherwise expand
img.src = img.src == "expand.png" ? "minimize.png" : "expand.png";
}
function HideRange(sect,elTag,IDS) {
var ContentObj = document.getElementById(sect);
var AllContentDivs = ContentObj.getElementsByTagName(elTag);
}
</script>
<ul id="ulist">
<li><p><img src="expand.png"/> Subject</p></li>
<div id="expand0" class="divInfo">Text</div>
<li><p><img src="expand.png"/> Subject</p></li>
<div id="expand1" class="divInfo">Text</div>
<li><p><img src="expand.png"/> Subject</p></li>
<div id="expand3" class="divInfo">Text</div>
</ul>
Here's a simple way to implement that - comments in the code
function ToggleList(IDS) {
HideRange('ulist','div',IDS); // not required unless using 'HideRange()' below
var CState = document.getElementById(IDS);
if (CState.style.display != "block") { CState.style.display = "block"; }
else { CState.style.display = "none"; }
// get a reference to the image contained in the <a> that was just clicked
var img = this.getElementsByTagName('img')[0];
// switch the graphic, if it's expand set it to collapse, otherwise expand
img.src = img.src == "img/expand.png" ? "img/collapse.png" : "img/expand.png";
}

Automatic slideshow with PHP and JavaScript

So basically i have made a PHP program that takes pictures from a folder and puts it into the "slideshow" in Gallery. The PHP code gives the images id's starting from "1" and so on.
Now with JavaScript i want it to automatically switch picture every 2,5 second. It actually runs as i want it to in my Firebug Script, but nothing happens in the browser. I already posted my JavaScript link in the bottom of the HTML body, and it doesn't help.
Any help would be appreciated.
<div id="gallery" class="grey">
<h3>Gallery</h3>
<div id="slideshow">
<?php
$path = "./img/gallery";
$all_files = scandir($path);
$how_many = count($all_files);
for ($i=2; $i<$how_many;$i++) {
$kubi=$i - 1;
echo "<img src=\"./img/gallery/$all_files[$i]\" id= \"$kubi\"/>";
}
?>
</div>
</div>
JavaScript code:
var picture = document.getElementById("1");
var i = 0;
function rotateImages() {
while (i < document.getElementById("slideshow").childNodes.length) {
picture.style.display = "none";
picture = picture.nextSibling;
picture.style.display = "inline";
i++;
};
};
window.onload = function(){
document.getElementById("1").style.display = "inline";
setInterval(rotateImages(), 2500);
};
What happens is that always uses the same first element picture, hides it and then shows the second image, it does not actually iterate through all the pictures.
In your code, picture always is the first element, next is always the second.
Also, it should not be a while loop since the callback is called once to change a picture, so change it to if, and reset to the first picture when it passes number of total elements.
It should be: (Javascript)
var firstPicture = document.getElementById("1");
var picture = firstPicture ;
var i = 0;
function rotateImages() {
// hide current element
picture.style.display = "none";
// choose who is the next element
if (i >= document.getElementById("slideshow").childNodes.length) {
i = 0;
picture = firstPicture;
} else {
picture = picture.nextSibling;
}
// show the next element
picture.style.display = "inline";
i++;
};
window.onload = function(){
var curImg = document.getElementById("1").style.display = "inline";
setInterval(rotateImages, 2500);
};

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

Hidden div flashing on page load

In my Rails app, I'm trying to hide a div (box) on page load in the Javascript function below. This function loops through a series of checkboxes with the same name (cb). If any of the checkboxes are checked, it should show the div.
function BoxCheck(cb,box){
var cbs=document.getElementsByName(cb);
var d=document.getElementById(box);
d.style.display = 'none';
var flag_check=0
for (var zxc0=0;zxc0<cbs.length;zxc0++){
if (cbs[zxc0].checked){
flag_check=flag_check+1
} else
{ }
}
if (flag_check > 0){
d.style.display = 'block';
document.getElementById('multi_control_spacer').style.display = 'block';
} else {
d.style.display = 'none';
document.getElementById('multi_control_spacer').style.display = 'none';
}
}
The function fires on load with:
<body onload="javascript:BoxCheck('doc_ids[]','multi_control');">
The problem is that when no checkboxes are selected, the div flashes on momentarily, and then disappears.
Here's the CSS:
#multi_control {
padding: 10px;
background: #333;
}
I tried setting the css to display:none, but then I can't seem to make it switch to back to display:block with Javascript.
Why not? Have you tried:
element.style.display = 'block';
How about putting style="display:none" into the div tag so it's hidden to begin with?

Categories