Suppose I have
<body>
<div id="stuff">
<div id="cat">a</div>
<div id="dog">b</div>
<div id="elephant">c</div>
<div id="rabbit">d</div>
<div id="frog">e</div>
</div>
</body>
So far the closet I could get was with JS,
document.getElement('body').onclick = function(e){
alert(e.target.innerHTML);
}
Which prints out the contents of the div when I want the literal div id like 'cat' or 'dog' not 'a' or 'b'. Also I am trying to accomplish this using jQuery, am I heading in the right direction?
You need to include jQuery js file in order to use jQuery methods.
With jQuery
$('body').click(function(e){
alert(e.target.innerHTML);
alert(e.target.id)
alert($(e.target).attr('id'));
});
With Javascript
document.getElement('body').onclick = function(e){
alert(e.target.innerHTML);
alert(e.target.id)
}
Sample html page using JQuery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery demo</title>
</head>
<body>
jQuery
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
document.getElement('body').onclick = function(e){
alert(e.target.innerHTML);
alert(e.target.id)
}
</script>
</body>
</html>
http://jsbin.com/ohotuv/1/edit
document.getElementById('stuff').onclick = function( e ){
alert( e.target.id );
};
jQ way:
$('#stuff').click(function( e ){
alert( e.target.id );
});
If it has not an ID, but has a CLASS (and you want it!) you can do:
http://jsbin.com/ohotuv/3/edit - (where "elephant" is a class)
$('#stuff').click(function( e ){
var name = e.target.id || e.target.className;
alert(name);
});
If you are using pure javascript you may need to make it cross browser compatible.
window.onload=function(){
document.getElementsByTagName('body')[0].onclick = function(e){
e = e ? e : window.event;
var source = e.target || e.srcElement;
alert(source.id);
}
}
I'd recommend reading up on jQuery.on().
In your example I'd recommend:
$("body").on("click", function(event){
alert($(this).id);
});
Although it's highly recommended to reduce the scope what what elements you're looking for the click event. For example:
$("#stuff").on("click", "div", function(event){
alert($(this).id);
});
Which would only handle ANY div element inside the html tag with the id of stuff. Reducing the context of handling events can help with encapsulation and debugging problems.
Related
I have the following HTML and JavaScript:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
Something
<div id="foo></div>
<script>
$(function() {
$link = $("#bar");
$link[0].click(function() {
alert("Whatever.");
});
});
</script>
</body>
</html>
This article explains the approach. However it's not working - no alertbox shows. Any ideas?
Just remove the [0] array index from the code and make sure to close div id quotes:
<html>
<head>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
Something
<div id="foo"></div>
<script>
$(function() {
$link = $("#bar");
$link.click(function() {
alert("Whatever.");
});
});
</script>
</body>
</html>
the $link[0] will return native element not jQuery object, use onclick event or addEventListener('click', ....)
$(function() {
$link = $("#bar");
$link[0].onclick = function() {
alert("Whatever.");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Something
<div id="foo"></div>
and the correct way to select element by index using jQuery is using eq()
$(function() {
$link = $("#bar");
$link.eq(0).click(function() {
alert("Whatever.");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Something
<div id="foo"></div>
please note that selector ID will only return 1 element so you can use second index or greater.
If you want to not open link but only alert any text you can try to write script something like that:
$('#bar').click(function(e) {
e.preventDefault();
alert('Whatever.');
})
If you are using id as a common selector than you are doing bad, please use class for common selector else you don't need to do something like $(id)[0]. Also, make a habit of unbinding the event once the binding is done.
$(function() {
$link = $("#bar");
$link.off('click').on('click', function() {
let $this = $(this);
let href = $this.attr('href');
alert("href " + href);
});
});
I'm trying to get the elements of the clicked source, but I don't know why it isn't working.
JSFIDDLE
HTML:
<span class="populate" onclick="populate();" href="?id=1">Hello</span>
CSS:
.populate {
cursor: pointer;
}
JS:
function populate(event) {
var event = event || window.event;
var src = event.srcElement;
var href = src.getAttribute('href');
alert(href);
}
The error I see in console is that the function populate is not defined.
Any help or suggestions will be appreciated!
The problem is with the order of the javascript and the span tag.
put the javascript function before the tag
JS
function populate(event) {
var event = event || window.event;
var src = event.srcElement;
var href = src.getAttribute('href');
alert(href);
}
html
<span class="populate" onclick="populate();" href="?id=1">Hello</span>
We need to define functions before calling them. Fiddle here
http://jsfiddle.net/HdvGD/7/
You code works fine in fiddle. The reason you didn't get it because you wrapped in onload() instead do it in No wrap in Head (fiddle at left top)
your fiddle1
Incase you want in onload() assign like variable
populate = function (event) {
var event = event || window.event;
var src = event.srcElement;
var href = src.getAttribute('href');
alert(href);
}
Check is fiddle2
Check this [answer to find the difference]
Update:
Sorry for pointing depreciated one(I'hv removed it). Event object "event" is not passed from the parameter. Actually here is a simple one
passing the event from onclick like
onclick="populate(event);"
then simple pass it and access like below
function populate(event) {
var src = event.target || event.srcElement;
var href = src.getAttribute('href');
alert(href);
}
Final Fiddle
Anchor tags contain href attribute
<a class="populate" id="link" onclick="populate(this.id);" href="......">Hello
</a>
function populate(id)
{
var someimage = document.getElementById(id);
var mysrc = someimage .src;
}
Use jquery to get it work as simple
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#populate").click(function(event) {
alert("As you can see, the link no longer took you to jquery.com");
var href = $('#populate').attr('href');
alert(href);
event.preventDefault();
});
});
</script>
</head>
<body>
<span class="populate" id="populate" onclick="populate();" href="?id=1" >Hello</span>
</body>
</html>
Your fiddle works fine, on the left-hand side, second drop-down, change to No Wrap - In <head>, now your content is there and script is loaded. Try it again: http://jsfiddle.net/HdvGD/4/
I'm very new to Jquery and looking to solve the reason a keydown event on a content editable div isn't cloning. I thought I had solved things when I discovered clone(true), but no my code still isn't working. The code below is a simplified version of what I'm trying to achieve.
Basically I'm attaching a keydown event to a content editable div then cloning it. However the cloned div isn't working like the original div.
I've been searching for a solution for a good while now and was hope someone could give me an answer so I can move on - many thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>untitled</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var mymax1 = 10;
$('#List_1').keydown(function(e){ check_charcount(mymax1, e); });
function check_charcount(mymax1, e)
{
<!--prevent line breaks, that is the enter key from working-->
if(e.keyCode==13){
e.preventDefault();
}
if(e.which != 8 && $('#List_1').text().length > mymax1{
$("#List_1").css("background-color","yellow");
e.preventDefault();
}
}
<!---->
var $cloned = $('#hope').clone(true);
$('#placeHere').append($cloned.html());
});
</script>
</head>
<body>
<div id="hope">
<div id="List_1" contentEditable="true">TEXT</div>
</div>
</br>
<div id="placeHere"></div>
</body>
</html>
Some things were not correct in your code as pointed Ian.
In your keydown function you are using $('list_1'), you should use reference to element.
BTW, clone keep id attr which mean that your cloned element get same id as original, which is not valid. See working code:
$(document).ready(function () {
var mymax1 = 10;
$('#List_1').keydown(function (e) {
check_charcount(mymax1, e);
});
function check_charcount(mymax, e) {
if (e.keyCode == 13) {
e.preventDefault();
}
if (e.which != 8 && $(e.target).text().length > mymax) {
$(e.target).css("background-color", "yellow");
e.preventDefault();
}
}
var $cloned = $('#hope').clone(true);
$('#placeHere').append($cloned.contents().removeAttr('id'));
});
SEE DEMO
is there anyway to get the class when click event is fired. My code as below, it only work for id but not class.
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id + " and " + event.target.class);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
click me 1
click me 2
</body>
</html>
jsfiddle code here
Try:
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id+" and "+$(event.target).attr('class'));
});
});
This will contain the full class (which may be multiple space separated classes, if the element has more than one class). In your code it will contain either "konbo" or "kinta":
event.target.className
You can use jQuery to check for classes by name:
$(event.target).hasClass('konbo');
and to add or remove them with addClass and removeClass.
You will get all the class in below array
event.target.classList
A variant on Vishesh answer, which instead returns a Boolean:
event.target.classList.contains(className)
$(document).ready(function() {
$("a").click(function(event) {
var myClass = $(this).attr("class");
var myId = $(this).attr('id');
alert(myClass + " " + myId);
});
})
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
</head>
<body>
click me 1
click me 2
</body>
</html>
This works for me. There is no event.target.class function in jQuery.
If you are using jQuery 1.7:
alert($(this).prop("class"));
or:
alert($(event.target).prop("class"));
Careful as target might not work with all browsers, it works well with Chrome, but I reckon Firefox (or IE/Edge, can't remember) is a bit different and uses srcElement. I usually do something like
var t = ev.srcElement || ev.target;
thus leading to
$(document).ready(function() {
$("a").click(function(ev) {
// get target depending on what API's in use
var t = ev.srcElement || ev.target;
alert(t.id+" and "+$(t).attr('class'));
});
});
Thx for the nice answers!
$(e.target).hasClass('active')
<script>
function clicky(e){
console.log(e) //the clicked element
}
</script>
<span onClick="clicky(this)">Clickable</span>
In the script above, the console.log(e) will give me the <span> that I clicked on.
Is there any way that I could omit the clicky(this) and still get the element?
It's because I don't want to put (this) all over the document.
Any answer are welcomed.
See this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<div id="foo" style="background:blue; width:100px; height:100px">
<script>
function clicky(e){
console.log(e);
}
var foo = document.getElementById("foo");
foo.onclick = function(e){clicky((e || window.event).target);}
</script>
</body>
</html>
You could try this, not tested though.
var spans = document.getElementsByTagName('span');
spans.attachEvent('click'.'clicky');
function clicky(e){
console.log(e) //the clicked element
}
or
var spans = document.getElementsByTagName('span');
for (i in spans)
{
spans[i].attachEvent('click'.'clicky');
}
function clicky(e){
console.log(e) //the clicked element
}
function clicky(e, elem){
<span onClick="clicky(event, this)">Clickable</span>
Or you could use Prototype or jQuery or any other library. I would improve your life.