HTML buttons will only work only on webpage re/-load - javascript

EDIT : Thanks to everyone who tried to help me. I appreciate the tips guys.
I changed my window.onloadand inserted the two event listeners inside of it.
After that I took the idea of #Ito Pizarro , and implemented it in my own way.
The result looks like this :
function openDoor() {
var x_1 = document.getElementById('img1');
var x_2 = document.getElementById('img2');
is_visible = (x_1.style.visibility == "hidden");
if (is_visible) {
x_1.style.visibility = "visible";
}
else {
x_2.style.visibility = "hidden";
}}
And I also did the same for my closeDoor() function.
END OF EDIT
I create a HTML page, with two buttons. Every button has its purpose when it's being clicked. The first one will show an image of an opened door. The second button will show an image of a close door. When the page is loaded no image is being shown. They appear only if their button is clicked.
Tried to created a nested if-statement with the a global bool that will make it run infinitely.
Also tried a for & while loop.
But I am new to programming and I struggle a bit.
window.onload = function () {
document.getElementById('OpenDoor').addEventListener("click", function () { openDoor() })
}
window.onload = function () {
document.getElementById('CloseDoor').addEventListener("click", function () { closeDoor() })
}
function openDoor(){
document.getElementById('img1').style.visibility = "visible";
}
function closeDoor(){
document.getElementById('img2').style.visibility = "visible";
}
In the code exist two problems :
I load the page and click the "close door" button and the closed door image appears. If I decide to open the door again by pressing the "open door" button, it wont do it.
I load the page and click the "open door" button first. The open door image appears and the if I click on the "close door" button and the image also appears, but I cant repeat the process by re-clicking the "open door" to reopen it.

You are assining a function on the onload event twice. By doing this the first delaration will never be triggered.
It should be more something like :
window.onload = function () {
document.getElementById('OpenDoor').addEventListener("click", function () { openDoor() })
document.getElementById('CloseDoor').addEventListener("click", function () { closeDoor() })
}
Don't forget to validate the answer if you have what you were looking for

EDIT: In addition to lucien-dulac's point about window.onload…
It looks like your two event handlers do a single thing to either of two separate elements.
openDoor() will only ever make #img1 visible.
closeDoor() will only ever make #img2 visible.
If you want subsequent clicks on #OpenDoor or #CloseDoor to change the visibility style of their respective target elements — #OpenDoor controls #img1, #CloseDoor controls #img2 — you would need to write a toggle into openDoor() and closeDoor().
Something like…
function openDoor(){
var el = document.getElementById('img1'),
is_visible = ( el.style.visibility === "visible" );
if ( is_visible ) {
el.style.visibility = "hidden";
} else {
el.style.visibility = "visible";
}
}

Related

Move color of an HTML element to another page

Good evening,
i was working on a part of what i hope will be my future website and i wanted to add a "photograpy" section to it, and here comes the problem.
since the title in the main page constatly changes color, i'd like to grab its current color to transfer it to the title of the other page to play an animation later on.
the problem is that when i press the related button, i am taken to the photograpy page, but the title remains black.
i've tried seraching for help on google but i haven't been able to find much.
here is the JS
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", function() {
loaded();
});
} else if (document.attachEvent) {
document.attachEvent("onreadystatechange", function() {
loaded();
});
}
function loaded() {
document.getElementById("PHtitle").style.color === titlecolor;
}
function script() {
const titlecolor = document.getElementById("title").style.color;
};
document.getElementById('photograpy').onclick = function () {
script();
};
The snippets don't allow for localStorage, so here is just the javascript.
First, I let the variables outside of a function. The titleColor function checks to see if titleColor was saved in localStorage, if not the default color is black.
Then I set the color of the phtitle to the contents of titleColor variable.
In the script function, I set the localStorage variable to the getComputedStyle color of the title.
Then last I use an event listener on the button to run the script for saving the color.
LocalStorage is a way to store data in the user's browser until they close their browser/clear their data etc.. Which will allow it to be usable on different pages then where it was saved.
let titleColor = localStorage.getItem("titleColor") || "#000000";
let PHtitle = document.querySelector("#PHtitle");
let title = document.querySelector("#title");
let btn = document.querySelector("#photography");
if(PHtitle){
PHtitle.style.color = titleColor;
}
function script() {
localStorage.setItem("titleColor", getComputedStyle(title).color)
}
if(btn && title){
btn.addEventListener("click", function() {
script();
})
}

Make an onclick event react different when click second time

I have a button on my website, which plays the music when you click on it and in the same time it changes the text inside of the button (to "Go to SoundCloud".)
I want that button (with the new text on it) to redirect to SoundCloud when I click on it.
Now I got both when click first time, which is redirect to SoundCloud and play the track. (plus it changes the text)
Any ideas, how to solve this problem? Thx!
var links = document.getElementById("playButton");
links.onclick = function() {
var html='<iframe width="100%" height="450" src="sourceOfMyMusic"></iframe>';
document.getElementById("soundCloud").innerHTML = html;
var newTexts = ["Go to SoundCloud"];
document.getElementById("playButton").innerHTML = newTexts;
newTexts.onclick = window.open('http://soundcloud.com/example');
};
Use a variable that indicates whether it's the first or second click.
var first_click = true;
links.onclick = function() {
if (first_click) {
// do stuff for first click
first_click = false;
} else {
// do stuff for second click
}
}
Just redefine the onclick after the first function call.
Put the onclick on the button instead of the html.
document.getElementById("playButton").onclick=window.open('http://soundcloud.com/example');
Another option in some cases is to use a ternary operator and a boolean toggle expression:
let btn = document.querySelector('.button');
let isToggledOn = false;
btn.addEventListener ('click', function(e) {
e.target.textContent = !isToggledOn ? 'Is ON' : 'Is OFF';
isToggledOn = !isToggledOn;
});
newTexts.onclick is not creating a function to open a window, it is simply taking the return value of window.open which is being executed right away.
It should look like:
newTexts.onclick = () => window.open('http://soundcloud.com/example');
Also this will not work as intended because newTexts is not the actual DOM element, you need to attach the new onclick on the element and not the array...
But to other answers in this page, the logic is hard to read, so I'd advise to refactor the logic to be more readable.

How can one <img> tag be used to execute 2 different js functions?

How can I set up one image, that when clicked changes to another image and then when clicked again reverts back to the original image while still carrying out functions independently. In my example I want a Play button that when pressed turns to a pause button. However I need to have both play and pause functionalities when the correct button is pressed. These work on do different buttons but I would like the one button to have all the functionality. I have tried a few things but everytime, one of the play/pause functions are not letting the other work.
$('#startSlider').click(function (){
if (document.getElementById("startSlider").src = "Play.png"){
document.getElementById("startSlider").src = "Pause.png";
scrollSlider();
}
else if (document.getElementById("startSlider").src != "Play.png"){
clearTimeout(tmOt);
document.getElementById("startSlider").src = "Play.png";
}
});
<img src="Play.png" id="startSlider"/>
problem is in your if block,
you are using = not ==
if (document.getElementById("startSlider").src = "Play.png"){// you are assigning here not comparing
you are assigning play.png every times when the click calls on the image.
you are using jquery then why are you not using this to make it more simple.
$('#startSlider').click(function (){
if (this.src == "play.png"){
this.src = "pause.png";
}else{
this.src = "play.png";
}
});
check this fiddle
I like using classes in these situations as it makes the code a little easier to follow:
$('#startSlider').click(function (){
$(this).toggleClass('pause')
if ( $(this).hasClass('pause') ) {
// Button is paused change to play
$(this).attr('src', 'Play.png')
// Pause function goes here
} else {
// Button is play change to pause
$(this).attr('src', 'Pause.png')
//play function goes here
}
})
You can do this with a little state machine. You keep the states inside an object, and handle the next state in the event listener of the button:
var states = {
_next: 'play',
next: function() {
return this[this._next]()
},
play: function() {
img.src = 'pause.jpg'
button.textContent = 'Pause'
this._next = 'pause'
},
pause: function() {
img.src = 'play.jpg'
button.textContent = 'Play'
this._next = 'play'
}
}
button.addEventListener('click', states.next.bind(states))
This is more of a general answer to your problem, that you'd have to adapt to your code.
DEMO: http://jsbin.com/moxoca/1/edit *
* The images might take a second to load.

Close image when clicked on outside $('html').click(); conflict with open image?

I have used a simple css and js for showing an image as popup when an image is clicked used and close button on top to close the image. Both openimage and closeimage are js functions
i have implemented as
open image function as
function imgv(x,y,img)
{
document.getElementById('imgv_i2').src = img;
document.getElementById('imgv_i2').style.width = x;
document.getElementById('imgv_i2').style.height = y;
document.getElementById('imgv_i2').width = x;
document.getElementById('imgv_i2').height = y;
imgToMiddle('imgv_i2');
document.getElementById('imgv_i2').style.display = 'block';
}
close image as
function closeimgv()
{
document.getElementById('imgv_i2').style.display = 'none';
document.getElementById('imgv_close').style.display = 'none';
}
event as
<img src="image src">
now for closing image when clicked on outside i have used these like
$('#imgv_i2').click(function(event){
event.stopPropagation();
});
$('html').click(function() {
if(document.getElementById('imgv_i2').style.display == 'block') {
closeimgv();
}
});
now what happens is when click for opening image triggered also the close image function also triggered how can i make the $('html').click(); bind after the open image function triggered and unbind after close image function. Thanks.
Try
$(document).click(function(ev) {
//avoid clicks on image itself
if($(ev.originalTarget).is("whatever triggers image opening")) {return;}
if(document.getElementById('imgv_i2').style.display == 'block') {
closeimgv();
}
});
I would recommend you to use jquery plugins for thick box or popup as they are very simple and easy to implement and customize. There are lots of open source plugins available try them out and they do provide the type of customization you are asking for !

Showing warning with timeout when opening external links

I want that when a user clicks on any external link (identified by either particular id or class) on my site then he should get a popup with a counter of 10 seconds, after 10 seconds the popup should close and the user should be able to access the external URL. How can this be done? I'm able to show a warning like below but I don't know how to add timeout to it, also this is a confirm box, not a popup where I can add some div and more stuff for user to see until the counter stops.
$(document).ready(function(){
var root = new RegExp(location.host);
$('a').each(function(){
if(root.test($(this).attr('href'))){
$(this).addClass('local');
}
else{
// a link that does not contain the current host
var url = $(this).attr('href');
if(url.length > 1)
{
$(this).addClass('external');
}
}
});
$('a.external').live('click', function(e){
e.preventDefault();
var answer = confirm("You are about to leave the website and view the content of an external website. We cannot be held responsible for the content of external websites.");
if (answer){
window.location = $(this).attr('href');
}
});
});
PS: Is there any free plugin for this?
I've put together a little demo to help you out. First thing to be aware of is your going to need to make use of the setTimeout function in JavaScript. Secondly, the confirmation boxes and alert windows will not give you the flexibility you need. So here's my HTML first I show a simple link and then created a popup div that will be hidden from the users view.
<a href='http://www.google.com'>Google</a>
<div id='popUp' style='display:none; border:1px solid black;'>
<span>You will be redirected in</span>
<span class='counter'>10</span>
<span>Seconds</span>
<button class='cancel'>Cancel</button>
</div>
Next I created an object that controls how the popup is displayed, and related events are handled within your popup. This mostly is done to keep my popup code in one place and all events centrally located within the object.
$('a').live('click', function(e){
e.preventDefault();
popUp.start(this);
});
$('.cancel').click(function()
{
popUp.cancel();
});
var popUp = (function()
{
var count = 10; //number of seconds to pause
var cancelled = false;
var start = function(caller)
{
$('#popUp').show();
timer(caller);
};
var timer = function(caller)
{
if(cancelled != true)
{
if(count == 0)
{
finished(caller);
}
else
{
count--;
$('.counter').html(count);
setTimeout(function()
{
timer(caller);
}, 1000);
}
}
};
var cancel = function()
{
cancelled = true;
$('#popUp').hide();
}
var finished = function(caller)
{
alert('Open window to ' + caller.href);
};
return {
start : start,
cancel: cancel
};
}());
If you run, you will see the popup is displayed and the countdown is properly counting down. There's still some tweaks of course that it needs, but you should be able to see the overall idea of whats being accomplished. Hope it helps!
JS Fiddle Sample: http://jsfiddle.net/u39cV/
You cannot using a confirm native dialog box as this kind of dialog, as alert(), is blocking all script execution. You have to use a cutomized dialog box non-blocking.
You can use for example: jquery UI dialog
Even this has modal option, this is not UI blocking.
Consdier using the javascript setTimeout function to execute an action after a given delay
if (answer){
setTimeOut(function(){
//action executed after the delay
window.location = $(this).attr('href');
}, 10000); //delay in ms
}

Categories

Resources