Event when a pair of elements are clicked - javascript

I have 5 elements with class .home and unique id's, and a button with class .btn1. When .home is clicked after .btn1 and vice versa, a function should be executed. I don't know what jQuery method i should use.

Try this :
<!DOCTYPE html>
<html>
<head>
<style>
.active {
background-color: skyblue;
}
</style>
</head>
<body>
<div class="home">I am Div1</div>
<div class="home">I am Div2</div>
<div class="home">I am Div3</div>
<div class="home">I am Div4</div>
<div class="home">I am Div5</div>
<button class="btn">Run</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
var divReady = false;
var btnReady = false;
$(".btn").on("click",function(){
btnReady = true;
$(this).addClass("active");
if (divReady)
fun();
})
$("div").on("click",function(){
divReady = true;
$("div").removeClass("active");
$(this).addClass("active");
if (btnReady)
fun();
})
function fun() {
alert("I am working!")
$(".btn,div").removeClass("active");
btnReady = false;
divReady = false;
}
})
</script>
</body>
</html>

I don't think there's a specific jQuery trick for that.
Why not use classes to store state?
$(function() {
$(".home").click(function () {
$(this).addClass("active");
if ($(".btn1").hasClass("active")) {
console.log("Doing something");
}
});
$(".btn1").click(function () {
$(this).addClass("active");
if ($(".home").hasClass("active")) {
console.log("Doing something");
}
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = 'home'>
Home
</div>
<div>
Stuff
</div>
<button class = 'btn1' >Button</button>
<div class = 'home'>
Home
</div>
<div>
Stuff
</div>
<div class = 'home'>
Home
</div>
<div>
Stuff
</div>
<div class = 'home'>
Home
</div>
<div>
Stuff
</div>

Simply count the times an event occured, and store the events. That can be easily done with an Array:
//create an array to store events
events=[];
//create a handler function
function handler(event){
//add the event to our array
events.push(event);
if(events.length==2){
//two events fired:
//first event:
a=events[0];
//second:
b=events[1];
//do whatever
}
}
//add an eventlistener that calls our handler and passes 'documentclick'
document.addEventListener("documentclick",function(){handler("click")});

Related

I'm trying to select multiple elements with the queryselectorall but it seems not working and i don't know why

I've tried the queryselector and it selects the first element. I've also tried this using a for loop but it didn't worked too, maybe I have been doing it wrong. Can someone help me with this?
<html>
<body>
<div id="list">
<div id="item1" class="bttn">Apple</div>
<div id="item2" class="bttn">Mango</div>
<div id="item3" class="bttn">Banana</div>
<div id="item4" class="bttn">Kiwi</div>
</div>
<style>
.bttn{
display: flex;
cursor: pointer;
}
</style>
<script>
var list = document.querySelectorAll(".bttn");
console.log(list);
list.onclick = function(){
this.style.background = "red";
};
</script>
</body>
</html>
You need to loop through your collection and apply the click listener to each matching element, and access that element inside the handler with event.target
<script>
var list = document.querySelectorAll(".bttn");
console.log(list);
list.forEach(el => el.addEventListener('click', function(e){
e.target.style.background = "red";
}))
</script>
You could abstract out the listener function if desired
<script>
let list = document.querySelectorAll(".bttn");
const onBttnClick = (e) => {
e.target.style.background = "red";
}
list.forEach(el => el.addEventListener('click', onBttnClick))
</script>
You're adding the onlick event listener to the Dom Element array.
You've to iterate over the array and assign the event listener to each element.
<html>
<body>
<div id="list">
<div id="item1" class="bttn">Apple</div>
<div id="item2" class="bttn">Mango</div>
<div id="item3" class="bttn">Banana</div>
<div id="item4" class="bttn">Kiwi</div>
</div>
<style>
.bttn{
display: flex;
cursor: pointer;
}
</style>
<script>
var list = document.querySelectorAll(".bttn");
console.log(list);
list.forEach(function(e){
e.addEventListener('click', function(){
this.style.background = "red";
}, false);
});
</script>
</body>
</html>

add event to element after it remove itself and append itself again

I tried to remove a button and alert() when i click it, then the function will append a 'same' button to a container div, after searching senior's legacy,
i tried to use on()/live()/delegate()/ unfortunately they not work.
<body>
<div id="container"></div>
<hr>
<button onclick="clicked()">Other one</button>
<hr>
</body>
<script>
$(document).ready(function(){
var i = 0;
$("#container").append("<button id='btn_sub' onclick='clicked()'>Click Me!</button>");
$("[id='btn_sub']").delegate(this,"click",function(){
$("#container").empty();
$("#container").append("<button id='btn_sub' onclick='clicked()'>Click Me!"+i+"</button>");
i++;
});//tried click/on click/live
});
function clicked(){
alert(1);
}
</script>
Finally, in this example, the clicked function put out of $(document).ready() and the part of alert worked.
Is there any other method to do the same effect?
and why on()/live()/delegate()/ not work?
Thanks.
First off $("[id='btn_sub']") can be replaced with $("#btn_sub"), then it's actually better to use a class as you might have many buttons.
This is a working example as an illustration: https://codepen.io/antoniandre/pen/XoNNpO
$(document).ready(function(){
$("#container").on("click", '.btn_sub', function() {
removeButton(this);
});
});
function addButton() {
$("#container").append("<button class='btn_sub'>Delete Me!</button>");
}
function removeButton(btn) {
btn.remove();
}
With the on() bound on the container, you actually make sure any matching button .btn_sub will get this event attached to them when they are created in the future.
Regarding live, it does the same as on but is now deprecated so you can forget it. https://api.jquery.com/live/#live-events-handler
Use on function to attach event.http://api.jquery.com/on/
$(document).ready(function () {
var i = 0;
$("#container").append("<button id='btn_sub' onclick='clicked()'>Click Me!</button>");
$("#container").on("click", "[id='btn_sub']", function(){
$("#container").empty();
$("#container").append("<button id='btn_sub' onclick='clicked()'>Click Me!" + i + "</button>");
i++;
});
});
function clicked() {
alert(1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div id="container"></div>
<hr>
<button onclick="clicked()">Other one</button>
<hr>
</body>
var i = 0;
var btn = "<button id='btn_sub' onclick='clicked()'>Click Me!</button>";
($(function(){
$("#container").append(btn);
$("#container").on("click", '#btn_sub', function() {
$("#container")
.empty()
.append($(btn).text($(btn).text() + " " + i++));
});
}));
function clicked() {
alert(i);
}
<body>
<div id="container"></div>
<hr>
<button onclick="clicked()">Other one</button>
<hr>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

This is about jquery 'append', i want know why and how to solve it

first, there are codes I wrote.
<body>
add
<div class="panel">
<div class="box"></div>
</div>
<div class="popup">
sure
cancel
</div>
<script>
$(function(){
$('#btn').click(function(){
$('.popup').show();
$('#sure').on('click', function(){
var $box = "<div class='box'></div>";
$('.panel').append($box);
});
$('#cancel').on('click', function(){
$('.popup').hide();
});
});
})
</script>
</body>
then,there are steps i did.
the result
why i click the cancel button at first, and next time i click Sure button, there appears two DIVs actually.I just want one div.
How to solve this problem?
Do not add the event-handler as many times you click on #btn.
Bind click handlers for "sure" and "cancel" out of the click handler for "#btn"
$(function() {
$('#btn').click(function() {
$('.popup').show();
});
$('#sure').on('click', function() {
var $box = "<div class='box'>Added</div>";
$('.panel').append($box);
});
$('#cancel').on('click', function() {
$('.popup').hide();
});
})
.popup {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
add
<div class="panel">
<div class="box"></div>
</div>
<div class="popup">
sure
cancel
</div>
If elements in the pop-up are created dynamically, Use Event delegation
$(function() {
$('#btn').click(function() {
$('.popup').show();
});
$(document).on('click', '#sure', function() {
var $box = "<div class='box'>Added</div>";
$('.panel').append($box);
});
$(document).on('click', '#cancel', function() {
$('.popup').hide();
});
})
.popup {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
add
<div class="panel">
<div class="box"></div>
</div>
<div class="popup">
sure
cancel
</div>

Button onclick doesn't change style.display of div

I have two divs, called loginpending and loggedin, which I am trying to configure so that once a button (button) is clicked, the divs will "flicker" between one being on and one being off.
For example, in this current state (with loginpending's display as block and loggedin's display as none), once the button is clicked, loginpending's display will become none and loggedin's display will become block through the function loginUpdate, which is then called through launch depending on what the state of each div is.
However, it doesn't work - the state of the buttons don't change at all once the button is clicked.
Help!
HTML code:
<div id="loginpending" style="display:block;">
Signup/Login here!
</div>
<div id="loggedin" style="display:none;">
Hello!
</div>
<button id="button" onclick="launch()">Hello!</button>
Javascript code (with Jquery):
var logincheck = 0;
function loginUpdate() {
"use strict";
$("#loginpending").toggle();
$("#loggedin").toggle();
}
function launch() {
"use strict";
var loginpending = document.getElementById("loginpending").style.display;
var loggedin = document.getElementById("loggedin").style.display;
window.alert(loginpending);
window.alert(loggedin);
if (loginpending === "none") {
logincheck = 0;
loginUpdate();
} else if (loggedin === "none") {
logincheck = 1;
loginUpdate();
} else {
logincheck = 0;
$("#loggedin").toggle();
}
}
Right now your button is submitting the from which refreshes the page reloadsin its original state.
You need to set the type of button to type="button"
<button id="button" type="button" onclick="launch()">Hello!</button>
$(document).ready(function() {
$('button').on('click', function(){
$('div').toggleClass('hidden');
})
});
.hidden {
display: none;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="loginpending" class="">
Signup/Login here!
</div>
<div id="loggedin" class="hidden">
Hello!
</div>
<button id="button" onclick="">Hello!</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript" src="sample.js"></script>
</body>
</html>
Code with jQuery
I tried to use your original code as much as I could.
var logincheck = 0;
$("#button").click(function() {
launch();
});
function loginUpdate() {
"use strict";
$("#loginpending").toggle();
$("#loggedin").toggle();
}
function launch() {
"use strict";
var loginpending = $("#loginpending").is(":hidden");
var loggedin = $("#loggedin").is(":hidden");
if(loginpending)
logincheck = 0;
else if (loggedin)
logincheck = 1
else
logincheck = 0;
loginUpdate();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="loginpending" style="display:block;">
Signup/Login here!
</div>
<div id="loggedin" style="display:none;">
Hello!
</div>
<button id="button" type="button">Hello!</button>
Gotta try this
$(function() {
var logincheck = 0;
function loginUpdate() {
"use strict";
$("#loginpending").toggle();
$("#loggedin").toggle();
}
$('#button').on('click', function(){
"use strict";
if(logincheck == 0) {
logincheck = 1;
}else{
logincheck = 0;
}
loginUpdate();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="loginpending" style="display:block;">
Signup/Login here!
</div>
<div id="loggedin" style="display:none;">
Hello!
</div>
<button id="button">Hello!</button>

jQuery: How to append something after one element?

DOM
<div id="a">
<div id="b"></div>
<div>
<p>Insert me after #b</p>
Requirement is insert p tag after '#b', and when the insert operation happened again, only replace the p tag instead of adding more.
Thanks for your help
This will insert it directly after #b, within #a, but if it already exists, then it wont insert it again.
$(document).ready(function(){
if ($('#newP').length == 0) {
$('#b').append('<p id="newP">Insert me after #b</p>')
}
});
Try this:
function insertP(html)
{
var a = $("#a");
var p = a.find("p")
if(p.length == 0)
{
p = $("<p></p>").appendTo(a);
}
p.html(html)
}
This function will remove an existing element then add a new element. If one does not exist it will simply add the element.
<body>
<script type="text/javascript">
$(document).ready(function() {
function addAfterB(pElement) {
if (!$('#b ~ p')) {
$(pElement).insertAfter('#b');
} else if ($('#b ~ p')) {
$('#b ~ p').remove();
$(pElement).insertAfter('#b')
}
}
addAfterB('<p>New Item 1</p>');
});
</script>
<div id="a">
<div id="b"></div>
<p>hello</p>
<div>
You can use $.after()...
<div id="a">
<div id="b"></div>
<div>
...
<script>
$("#b").after("<p>Insert me after #b</p>");
</script>

Categories