Short version: I need a button to carry out three seperate actions when clicked three times.
Long version: I have one page of my site where there is a little readable introduction with illustrations. I have a button that changes the first image to a second one when clicked once. When the user has finished reading the second image, clicking the same button then navigates to a different html location, using a multiclick function.
However, I need to add a third image to the introduction. I therefore need the button to change image1 to image2 on the first click, change image2 to image3 on the second click, then navigate to the next html location on the third click.
Is this possible? All of the multiclick solutions I've seen so far only cover two events. Or they use 'onclick', which I've been advised is bad practice. Can I modify the code I already have to add a third click action (maybe changing the value of calledonetime)? Or am I going in completely the wrong direction?
Working JS code for two actions:
<script>
jQuery(document).ready(function () {
$('#multiclick').click(function () {
multiclick();
});
});
var calledonetime = false;
function multiclick() {
if(calledonetime=== false) {
calledonetime = true;
var image = document.getElementById("infoscreentext");
image.src="infoscreentext2.png"; } /* action on first click */
else {
window.location.href = "castleview.html"; /* action on second click */
}
}
</script>
The HTML:
<body>
<div id="wrapper" div class="toshow">
<img src="infoscreenarrows.jpg" alt="Title" />
<img src="infoscreentext.png" id="infoscreentext" alt="" />
</div>
<div id="enterbutton">
<input type=image id=multiclick img src="silvercogarrow.png" alt="Enter" >
</div>
</body>
You can use a switch:
var clickCount = 0;
function clickHandler () {
clickCount += 1;
switch (clickCount) {
case 1:
// do action #1
break;
case 2:
// do action #2
break;
case 3:
// do action #3
break;
}
}
Or you can use an Array:
var clickCount = -1;
var actions = [];
function action1 (e) { /* prevent default, switch to image 1 */ }
function action2 (e) { /* prevent default, switch to image 2 */ }
function action3 () { /* follow hyperlink */ }
actions.push(action1);
actions.push(action2);
actions.push(action3);
function clickHandler (event) {
clickCount += 1;
actions[clickCount](event);
}
I would say do it with three different clicks as below with css html and js
<script>
jQuery(document).ready(function () {
$('#multiclick').click(function () {
multiclick();
});
});
var image1 = document.getElementById("infoscreentext");
var image2 = document.getElementById("infoscreentext2");
var image3 = document.getElementById("infoscreentext3");
image1 && image1.addEventListener('click', () => {
image1.classList.add('hide');
image2.classList.remove('hide');
});
image2 && image2.addEventListener('click', () => {
image2.classList.add('hide');
image3.classList.remove('hide');
});
image3 && image3.addEventListener('click', () => {
window.location.href = "castleview.html";
});
</script>
.hide {
display: none;
}
<body>
<div id="wrapper" div class="toshow">
<img src="infoscreenarrows.jpg" alt="Title" />
<img src="infoscreentext.png" class="" id="infoscreentext" alt="" />
<img src="infoscreentext2.png" class="hide" id="infoscreentext2" alt="" />
<img src="infoscreentext3.png" class="hide" id="infoscreentext3" alt="" />
</div>
<div id="enterbutton">
<input type=image id=multiclick img src="silvercogarrow.png" alt="Enter" >
</div>
</body>
Yes this is possible and so easy but why do you use a boolean for that? I suggest using an Integer for that, so let's start:-
<script>
jQuery(document).ready(function () {
$('#multiclick').click(function () {
multiclick();
});
});
var clickedCount = 0;
function multiclick() {
clickedCount++;
if(clickedCount == 1) {
var image = document.getElementById("infoscreentext");
image.src="infoscreentext2.png"; /* change image on first click */
var calledonetime[1];
} /* add 1 count to calledonetime */
else if(clickedCount == 2) {
var image = document.getElementById("inforscreentext2");
image.src="infoscreentext3.png"; } /* change image on second click */
else {
window.location.href = "castleview.html"; /* action on third click */
}
}
</script>
Related
Hey guys I am currently creating a newsletter popup.
I'm wanting to hide the div after the close button is selected using a cookie. The code snippet I've taken does include some code to try and achieve this but doesn't seem to work for me. Anyone know a solution?
JS
var delay = 0; //in milliseconds
jQuery(document).ready(function($){
setTimeout(function(){
showNewsletterPopup();
}, delay);
jQuery('.popup-close').click(function(){
$('.newsletter-overlay').hide();
});
});
function showNewsletterPopup(){
jQuery('.newsletter-overlay').show();
}
function onLoad() {
var showDiv;
if(localStorage.getItem("showDiv") == null) {
showDiv = true;
}
else {
showDiv = localStorage.getItem("showDiv")
}
if (showDiv) {
document.getElementById('newsletter-overlay').style.display = 'block';
}
else {
document.getElementById('newsletter-overlay').hide();
}
}
function onClose() {
document.getElementById('newsletter-overlay').remove();
localStorage.setItem("showDiv", false);
}
HTML
<div class="newsletter-overlay">
<div id="newsletter-popup">
<img src="/wp-content/uploads/static/TLTX.svg">
<div class="col1">
<div class="newsletter-in">
<h3>Take 10% off your first purchase</h3>
<p class="modalp">Join our Tribe! Our mates get the best rates. Every $1 spent will earn you 1 point. Be the first to know about new arrivals. Receive 10% off your first order! See more on our Tribe page
[wc_reg_form_bbloomer]
</div>
</div>
</form>
</div>
</div>
</div>
the provided code is a bit messy... there are some unused functions and a lot of noise. however, here is my proposal:
$(document).ready(function($) {
const $newsletterPopup = $('#newsletter-popup');
const $newsletterOverlay = $('.newsletter-overlay');
const $popupCloseLink = $('.popup-close');
let showDiv = JSON.parse(localStorage.getItem("showDiv"));
if (showDiv === null) {
showDiv = true;
}
if (showDiv) {
$newsletterOverlay.show();
$newsletterPopup.show();
} else {
$newsletterOverlay.hide();
$newsletterPopup.hide();
}
$popupCloseLink.click(function() {
$newsletterOverlay.hide();
$newsletterPopup.hide();
localStorage.setItem("showDiv", false);
});
});
I have created a function which is used in an event listener function so when the user clicks the left arrow icon on the webpage, a different character image is displayed. The first click works fine and the image is changed, however on the second click, nothing happens. I can't figure out why as from what I can see, the condition of the 'else if' of the statement is true so therefore the src code should change accordingly and change the image.
There are no error messages in the console.
Here is the Event listener:
document.querySelector(".left").addEventListener("click", () => {
leftArrow();
});
Here is the leftArrow function:
leftArrow: () => {
if (document.querySelector(DOMStrings.characterImg).src = characters[0]) {
document.querySelector(DOMStrings.characterImg).classList.add("boris");
document.querySelector(DOMStrings.characterImg).src = characters[1];
const el = document.querySelector(DOMStrings.characterImg);
console.log(el);
} else if (document.querySelector(DOMStrings.characterImg).src = characters[1]) {
document.querySelector(DOMStrings.characterImg).classList.remove("boris");
document.querySelector(DOMStrings.characterImg).src = characters[0];
const el = document.querySelector(DOMStrings.characterImg);
console.log(el);
}
Here is where the images are stored:
const characters = ["Resources/Images/trump.png", "Resources/Images/boris.png"];
Here is where the DOM strings are stored:
const DOMstrings = {
characterImg: ".character-img"
}
Lastly, here is the relevant html:
<div class="character-select">
<ion-icon class="left" name="arrow-dropleft-circle"></ion-icon>
<ion-icon class="right" name="arrow-dropright-circle"></ion-icon>
<img class="character-img" src="Resources/Images/trump.png">
</div>
function myFunction() {
document.getElementById("myImg").src = "https://www.w3schools.com/jsref/hackanm.gif";
}
function myFunctionbygeneric(){
document.querySelector(".test").src = "https://www.w3schools.com/jsref/hackanm.gif";
}
function myFunctionbygenericid(){
document.querySelector("#myImg").src = "https://www.w3schools.com/jsref/compman.gif";
}
<img id="myImg" class="test" src="https://www.w3schools.com/jsref/compman.gif" width="107" height="98">
<button onclick="myFunction()">click here</button>
<button onclick="myFunctionbygenericid()">Query selector by id</button>
<button onclick="myFunctionbygeneric()">Query selector</button>
Use can use like this
let myImage = document.querySelector('img');
myImage.onclick = function() {
let mySrc = myImage.getAttribute('src');
if(mySrc === 'https://www.w3schools.com/jsref/compman.gif') {
myImage.setAttribute ('src','https://www.w3schools.com/jsref/hackanm.gif');
} else {
myImage.setAttribute ('src','https://www.w3schools.com/jsref/compman.gif');
}
}
<img src="https://www.w3schools.com/jsref/hackanm.gif" />
How can I make a HTML button act like a toggle? I have two JS functions that modify an image, one to a new image and the other to change it back. How can I make sure a button activates the first function when pressed the first time but then activates the second when pressed again, repeated for the third and fourth time etc.
document.getElementById("baseImg").src = "assets/1stImg.png";
function imgChange1() {
document.getElementById("baseImg").src = "assets/2ndImg.png";
}
function imgBack1() {
document.getElementById("baseImg").src = "assets/1stImg.png";
}
<img id="baseImg">
<button onclick="imgChange1()">Change</button>
How would I go about including the second function within this button?
`
I don't really get your question because you were saying "toggle" but you were saying
How can I make sure a button activates the first function when pressed
the first time but then activates the second when pressed again?
But well, here's how you do it:
var clicked = false;
function toggleBtnClick(button) {
var img = document.getElementById('baseImg');
if (clicked) { //this will be executed on future clicks after first click
img.src = 'http://via.placeholder.com/350x150/4CAF50/000000';
console.log('Next click');
//or do something else
} else { //this will only be executed once
img.src = 'http://via.placeholder.com/350x150/e9e9e9/000000';
console.log('First click');
}
clicked = true; //update to true after first click
}
button {
position: absolute;
right: 0;
}
<img id="baseImg" src="http://via.placeholder.com/350x150/3fafed/000000">
<button onclick="toggleBtnClick()">Change</button>
But, if you really want a "toggle" functionality, here's how you do it:
var clicked = false;
function toggleBtnClick() {
var img = document.getElementById('baseImg');
if (clicked) {
img.src = 'http://via.placeholder.com/350x150/e9e9e9/000000';
clicked = false;
} else {
img.src = 'http://via.placeholder.com/350x150/3fafed/000000';
clicked = true;
}
}
button {
position: absolute;
right: 0
}
<img id="baseImg" src="http://via.placeholder.com/350x150/e9e9e9/000000">
<button onclick="toggleBtnClick()">Change</button>
I am trying to make a function that would allow me to toggle eventListener of an element.
In the example below, I have three buttons: main, on and off. When I click on the on button, the main button becomes functional. After I click off button, the main button should not work anymore (but now it still does).
Now I can achieve a desired behavior by clicking on button for the second time, but I guess it's a bad coincidence and it's not supposed to work that way.
Maybe I should add that I would like to work this out without using jQuery or similar and it needs to be a function, because I am going to use it for a lot of buttons.
(I suspect something with scope causes the problem (clickHandler when calling the function to activate the button is not the same as the clickHandler when calling the function to disable the button), but I can't think of a way to test it.)
// buttons definitions, not important
var mainButton = document.querySelector("#mainButton");
var onButton = document.querySelector("#onButton");
var offButton = document.querySelector("#offButton");
// main function
var toggleButtons = function(toggleVal, button, element) {
var activateButton, clickHandler, disableButton;
// callback function for listener bellow
clickHandler = function() {
document.querySelector(element).classList.toggle("yellow");
};
activateButton = function() {
button.addEventListener("click", clickHandler);
};
disableButton = function() {
button.removeEventListener("click", clickHandler);
};
// when first argument is 1, make the button functional, otherwise disable its functionality
if (toggleVal === 1) {
activateButton();
} else {
disableButton();
}
};
// when onButton is clicked, call main function with arguments
// this works
onButton.addEventListener("click", function() {
toggleButtons(1, mainButton, "body");
});
// this fails to disable the button
offButton.addEventListener("click", function() {
toggleButtons(0, mainButton);
});
.yellow {
background-color: yellow;
}
<button type="button" id="mainButton">mainButton
</button>
<button type="button" id="onButton">onButton
</button>
<button type="button" id="offButton">offButton
</button>
<p>mainButton: toggles background color on click
</p>
<p>onButton: turns on mainButtons's functionality</p>
<p>offButton: supposed to turn off mainButton's functionality</p>
var mainButton = document.querySelector("#mainButton");
var onButton = document.querySelector("#onButton");
var offButon = document.querySelector("#offButton");
var element; // declare the element here and change it from toggleButtons when needed.
function clickHandler() {
document.querySelector(element).classList.toggle('yellow');
}
function activateButton(button) { // You missed this part
button.addEventListener('click', clickHandler);
}
function disableButton(button) { // You missed this part
button.removeEventListener('click', clickHandler);
}
function toggleButtons(value, button) {
if (value === 1) {
activateButton(button); // You missed this part
} else {
disableButton(button); // You missed this part
}
};
onButton.addEventListener('click', function() {
element = 'body'; // you can change it to some other element
toggleButtons(1, mainButton);
});
offButton.addEventListener('click', function() {
element = 'body'; // you can change it to some other element
toggleButtons(0, mainButton);
});
Below code helps to toggle between two functions from an eventListener:
var playmusic=false;
function playSound() {
const audio = document.querySelector(`audio[data-key="${event.keyCode}"]`)
audio.currentTime = 0
audio.play()
playmusic=true;
}
function stopSound() {
const audio = document.querySelector(`audio[data-key="${event.keyCode}"]`)
audio.pause()
playmusic=false;
}
window.addEventListener('keydown',
function(){playmusic?stopSound():playSound()} )
In an earlier question I posted, someone mentioned that I can combine two handlers together to save myself from typing code twice. The two click handlers I have below do duplicate code, but I'm not sure how to organize them into one function so that when I click the left arrow button, the function knows I clicked the left button and responds accordingly, and likewise with the right arrow button. I imagine that I'll have an if statement but do I need to have each button run an argument through the function? How do I do that?
The code below loops through a list of images in the HTML and finds the appropriate image to place on the lightbox. I can go through the list from top to bottom and bottom to top. I can also move from the first child to the last child and vice versa. I'm just not sure if these two can be combined together or not.
These buttons are programmatically appended to the overlay.
var $arrowLeft = $('<button id="left" class="arrow">‹</button>');
var $arrowRight = $('<button id="right" class="arrow">›</button>');
Left and right arrow handlers:
//When left arrow is clicked
$arrowLeft.click(function() {
$('#imageGallery li a img').each(function() {
var galleryImage = $(this);
if (galleryImage.attr('src') === $image.attr('src')) {
var li = galleryImage.closest('li');
if (li.is(':first-child')) {
var gallery = li.parent();
var lastLi = gallery.children(':last-child');
var anchor = lastLi.children('a');
var image = anchor.children('img');
$image.attr('src', image.attr('src'));
} else {
var prevLi = li.prev();
var anchor = prevLi.children('a');
var image = anchor.children('img');
$image.attr('src', image.attr('src'));
}
return false;
}
});
});
//When right arrow is clicked
$arrowRight.click(function() {
$('#imageGallery li a img').each(function() {
var galleryImage = $(this);
if (galleryImage.attr('src') === $image.attr('src')) {
var li = galleryImage.closest('li');
if (li.is(':last-child')) {
var gallery = li.parent();
var firstLi = gallery.children(':first-child');
var anchor = firstLi.children('a');
var image = anchor.children('img');
$image.attr('src', image.attr('src'));
} else {
var nextLi = li.next();
var anchor = nextLi.children('a');
var image = anchor.children('img');
$image.attr('src', image.attr('src'));
}
return false;
}
});
});
HTML:
<body>
<h1>Image Gallery</h1>
<ul id="imageGallery">
<li><img src="images/refferal_machine.png" width="100" alt="Refferal Machine By Matthew Spiel"></li>
<li><img src="images/space-juice.png" width="100" alt="Space Juice by Mat Helme"></li>
<li><img src="images/education.png" width="100" alt="Education by Chris Michel"></li>
<li><img src="images/copy_mcrepeatsalot.png" width="100" alt="Wanted: Copy McRepeatsalot by Chris Michel"></li>
<li><img src="images/sebastian.png" width="100" alt="Sebastian by Mat Helme"></li>
<li><img src="images/skill-polish.png" width="100" alt="Skill Polish by Chris Michel"></li>
<li><img src="images/chuck.png" width="100" alt="Chuck by Mat Helme"></li>
<li><img src="images/library.png" width="100" alt="Library by Tyson Rosage"></li>
<li><img src="images/boat.png" width="100" alt="Boat by Griffin Moore"></li>
<li><img src="images/illustrator_foundations.png" width="100" alt="Illustrator Foundations by Matthew Spiel"></li>
<li><img src="images/treehouse_shop.jpg" width="100" alt="Treehouse Shop by Eric Smith"></li>
</ul>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/app.js" type="text/javascript" charset="utf-8"></script>
</body>
You may either use (as already answered) the target to determine the button.
You may also have two handlers which call the same function, I made an example to explain what I mean, I hope you understand the principle (Did not test it)
//When left arrow is clicked
$arrowLeft.click(function() {
moveImages(true);
});
//When right arrow is clicked
$arrowRight.click(function() {
moveImages(false);
});
function moveImages(topToBottom) {
var ttb = ':last-child';
if(topToBottom) {
ttb = ':first-child';
}
$('#imageGallery li a img').each(function() {
var galleryImage = $(this);
if (galleryImage.attr('src') === $image.attr('src')) {
var li = galleryImage.closest('li');
if (li.is(ttb)) {
var gallery = li.parent();
var aLi = gallery.children(ttb);
var anchor = aLi.children('a');
var image = anchor.children('img');
$image.attr('src', image.attr('src'));
} else {
var theLi;
if(topToBottom) {
theLi = li.next();
} else {
theLi = li.prev();
}
var anchor = theLi.children('a');
var image = anchor.children('img');
$image.attr('src', image.attr('src'));
}
return false;
}
});
};
Your callback have event parameter which contains which key has been pressed.
$('a').mousedown(function(f) {
if (f.which == 0) {
alert('left button')
}
else if(f.which == 2) {
alert("right click");
}
})
According to W3C its values should be:
Left button – 0
Middle button – 1
Right button – 2
Use e.target to find out which button was clicked.
Something along these lines:
$('a.arrows').on('click', function(e) {
// ... your common variables here
if(e.target.id === 'leftArrow') {
// ... your logic for left arrow
} else {
// ... your logic for right arrw
}
});
Where arrows is a class that you could put on your arrow buttons. Alternatively, you could bind your click handler to a parent element. Logic remains the same.
Try this : You can bind click event handler using id selector as shown below. You can identify the clicked button whether it is left or right using id of the button and create logic accordingly.
$(document).on('click','#left, #right' ,function() {
var id = $(this).attr('id');
var liCheck = ':first-child';
var childCheck = ':last-child';
//for right button swap the child and li check
if(id == 'right')
{
childCheck = ':first-child';
liCheck = ':last-child';
}
$('#imageGallery li a img').each(function() {
var galleryImage = $(this);
if (galleryImage.attr('src') === $image.attr('src')) {
var li = galleryImage.closest('li');
if (li.is(liCheck)) {
var gallery = li.parent();
var childLi = gallery.children(childCheck);
var anchor = childLi.children('a');
var image = anchor.children('img');
$image.attr('src', image.attr('src'));
} else {
var childLi = li.prev();
//for right button update child li
if(id == 'right')
{
childLi = li.next();
}
var anchor = childLi.children('a');
var image = anchor.children('img');
$image.attr('src', image.attr('src'));
}
return false;
}
});
});