Could someone explain why the clicking on button1 doesn't get captured? I know return false on event click will stop the propagation, but it should still capture the element by document.addEventListener('click', function(e) {console.log(e.target);}); because we are trying to capture directly the main element via e.target not its parent element.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#button1").click(function(){
return false;
});
});
</script>
</head>
<body>
<button id="button1">Button1 (dont get captured)</button>
<button id="button2">Button2 (get captured)</button>
<script>
document.addEventListener('click', function(e) {
console.log(e.target);});
</script>
</body>
</html>
I can't change that jQuery code $("#button1").click(function(){return false});, but still, want to capture the button1 element when it gets clicked (with javascript), is there any workaround?
i could bind another event handler to button1 like this document.getElementById("button1").addEventListener("click", function(e){console.log(e.target)}); in real there are many many elements which I want to capture (with different classes and id), it would be impractical to add an event listener to each of them, I showed one button just for an example. , I just simply want to log whichever element is clicked.
I can't change the jQuery code or HTML of the page, i want to run some tests in chrome console only, for which i want to capture each element which is clicked
thanks
The return false; prevents the browser from performing the default action for button1 link.
The equivalent code for return false is:
$('.button1')
.click(function (event) {
event.preventDefault();
event.stopPropagation();
});
If you just want to stop propagation use stopPropagation().
Take a look at this, and read more about preventDefault() and stopPropagation()
Not very efficient but worked for me
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#button1").click(function(){
return false;
});
});
</script>
</head>
<body>
<button id="button1">Button1 (dont get captured)</button>
<button id="button2">Button2 (get captured)</button>
<script>
elements = document.querySelectorAll('body *');
elements.forEach(function(elem) {
elem.addEventListener('click', function(e){
console.log(e.target); // or simply console.log(elem)
});
});
</script>
</body>
</html>
Thanks to everyone, especially #mplungjan who gave me this idea
Related
I am trying to get jQuery to copy an element's title attribute when it is clicked, but I think I'm having a problem with event bubbling.
I can do this easily enough with straight JS, but I'm trying to understand how to do this with jQuery.
Here is my code:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<p class="copy" title="actual text to be copied">Hello world.</p>
<script>
$('document').ready(function(){
$(".copy").on({
click: function(e) {
document.execCommand("copy");
},
copy: function(event) {
if (event.originalEvent.clipboardData) {
// allegedly copies the text to the clipboard
event.originalEvent.clipboardData.setData("text/plain", $(this)[0].title);
// show us what was copied.
alert(event.originalEvent.clipboardData.getData("text"));
}
}
});
});
</script>
</body>
</html>
event.clipboardData doesn't exist, but event.originalEvent.clipboardData, so I'm working with that.
But I think the problem is that event.originalEvent.clipboardData is not actually the clipboard. But jQuery doesn't seem to expose that part of the API to it's own event.
Do I make jQuery apply it to the actual event rather than to originalEvent? If yes, then how so?
Here's a jsbin: https://jsbin.com/borumexuga/edit?html,js,output
Insert event.preventDefault(); inside the if.
https://jsbin.com/guwowomece/1/edit?html,js,output
Please consider this test:
Main file:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
var secondwindow = false;
$(function() {
secondwindow = window.open("secondwindow.html");
$(secondwindow).load(function() {
secondwindow.setWindow(window);
})
$("#custom").click(function() {
$(document).trigger("custom");
});
});
</script>
</head>
<body>
<button id="click">Click event</button>
<button id="custom">Custom event</button>
</body>
</html>
Second (popup) file:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
var mainwindow = false;
function setWindow(obj) {
mainwindow = obj;
$(mainwindow.document).on("click", function() {
$("body").append("<p>Click event from main window</p>");
});
$(mainwindow.document).on("custom", function() {
$("body").append("<p>Custom event from main window</p>");
});
};
</script>
</head>
<body>
</body>
</html>
My goal is to add a event listener in the second window for custom events in the main window.
What I found, and this test can proves, is that event listening to other window works for "standard" events like click and not for custom events.
Can you tell me if this is a jQuery limitation or I'm missing something?
(I'm sorry I could not put that code in a jsfiddle because window.open doesn't work very well with jsfiddle)
The problem is that you need to take into account the jQuery instance you're using to define your targets and trigger.
secondwindow.html -> $(mainwindow.document)
is not the same as
main.html -> $(document)
It needs to be:
secondwindow.html -> mainwindow.$(mainwindow.document)
Or reverse it:
main.html -> secondwindow.$(document)
secondwindow.html -> $(mainwindow.document)
jQuery events are managed by jQuery.event object, and this is tied to the instance of jQuery that's being used. You can for example get which events are registered this way:
$.event.global
You'll see that the events registered are not only dependent on the selectors themselves, but on the jQuery instance as well. And this is the case for click event as well as custom events.
I am using JQuery's .click function and I have multiple buttons on my website. Clicking one button will execute every .click function in my HTML document. Is there a way to make one button execute one .click? I have included some code below to illustrate my problem. Clicking the first button called "Click Me!" will execute all the functions in my HTML document. How would I make it so that the button "Click Me!" does not execute every function in my document?
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>
My Website
</title>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
</head>
<body>
<button>
Click Me!
</button>
<button onclick="document.body.style.backgroundColor='blue';">
Change BG color
</button>
<script>
$(document).ready(function () {
$("button").click(function(){
$("#d").hide();
});
});
$(document).ready(function () {
$("button").click(function(){
$("#f").fadeToggle(3000);
});
});
</script>
<button>Toggle fade</button>
<div>
<p id="d">Some text here.</p>
</div>
<div>
<p id="f">Some text to fade.</p>
</div>
</body>
</html>
*Update
So I have changed my script to the following:
$(document).ready(function () {
$('#button1').click(function(){
$("#d").hide();
});
});
Nothing happens when I click the button though. Is this the correct syntax? This syntax was used on W3Schools.
If you use $("button"), the click() function you provide will apply to ALL buttons. I would recommend giving your button an id and then use:
$("#myButtonId").click(function(){
$("#d").hide();
});
JQuery selectors are very useful for targeting your elements in the DOM.
Yep. Put an ID or Class on that button so you can select it with more specificity.
<button id="button1">foo</button>
<button id="button2">bar</button>
$('#button1').on('click', function(){ $("#d").hide(); });
$('#button2').on('click', function(){ console.log("button2"); });
You should give the button and ID or class like so:
<button id="myButton">Test</button>
And then use the following click event:
$("#myButton").click(function(){
...
});
This isn't something I really want to do, just wondering if it's possible.
Say I have a page like this, which is just a heading and an input box.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>2014-4-24-01</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function jQuerySetup() {
if($) {
$(document).ready( function () {
$("body").on("keypress", "input", function ( event ){
if(event.keyCode == 13){
$("body").get(0).innerHTML = this.value;
}
});
});
} else {
window.setTimeout(jQuerySetup, 250);
}
}
jQuerySetup();
</script>
</head>
<body>
<h3>Test</h3>
<input type="text" width="20">
<div id="testDiv"></div>
</body>
</html>
If I type the following into the input box and hit enter, nothing happens. Why is that?
<script>window.setTimeout(function () { alert("Uh oh"); }, 1000);</script>
EDIT: And I know that it's very easy for someone to run JavaScript through the console window and achieve a similar effect. But my question is more of understanding why the above isn't possible (or why I'm not getting it right).
innerHTML won't execute the script, use jQuery html instead.
$("body").html(this.value);
It is possible to run script from an input box using eval(). The way you are doing it won't work since the specification states that scripts inserted via .innerHTML should not be executed (it's a large green note at the end of the section).
From the w3c spec...
Note: script elements inserted using innerHTML do not execute when they are inserted.
Instead just use eval
You don't need if($) { and setTimeout because it's handled by $(document).ready.
You can try that:
<script>
$(document).ready( function () {
$("body").on("keypress", "input", function ( event ){
if(event.keyCode == 13){
$("body").get(0).innerHTML = this.value;
}
});
});
</script>
Working example here
I am trying to grab an element (a button) and add an event listener on it.
Whenever I run
var button = document.getElementById('clickMe');
console.log(button); // null
I checked that my javascript file is loading and checked that everything is case sensitive. Here is my html and JS Files:
HTML:
<!doctype html>
<html>
<head>
<script src="js/timer.js"></script>
</head>
<body>
<button id='clickMe' type='button'>Hello</button>
</body>
</html>
JS
var button = document.getElementById('clickMe');
console.log(button);
function buttonClicked () {
alert('the button was clicked');
}
button.addEventListener('click', buttonClicked);
function timerComplete () {
alert('timer complete');
}
setTimeout(timerComplete, 2000);
The most common errors I have found was camel casing getelementbyid which I did.
Does anyone know why I keep getting null? Is it trying to grab the element before it is loaded?
Your Javascript code is executed before the Button is added to the DOM. You could change your HTML to this:
<!doctype html>
<html>
<body>
<button id='clickMe' type='button'>Hello</button>
<script src="js/timer.js"></script>
</body>
</html>
Or even better, if you don't mind making your JS code a bit more complex you could wait for your dom elements to be loaded before executing that part of the code:
document.addEventListener('DOMContentLoaded', function() {
var button = document.getElementById('clickMe');
console.log(button);
});
If you use this JS you can put back your script tag back to the head