click event for links - javascript

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);
});
});

Related

Rewrite random/button Javascript without jQuery

I’ve this script. It works fine in this situation, but it seems to conflict with other scripts in the site I'm working on. How can I rewrite it that it doesn't need jQuery / OnLoad?
This is what it does: the button opens a random link from an array in a new window everytime you click on it.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.js"></script>
<title>TestBase</title>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
var links = [
"http://vetteletters.nl",
"http://todont.co",
"http://planetx.nl/titles"
];
$("#rnd_link").click(function(){
window.open(links[Math.floor((Math.random()*3))]);
});
});//]]>
</script>
</head>
<body>
<button id="rnd_link">Random</button>
</body>
</html>
window.onload = function(){
var links = [
"http://vetteletters.nl",
"http://todont.co",
"http://planetx.nl/titles"
];
var btn = document.getElementById('rnd_link');
btn.onclick = function(){
window.open(links[Math.floor((Math.random()*3))]);
}
}//]]>
Should work.
This works:
<script type='text/javascript'>
var links = [
"http://vetteletters.nl",
"http://todont.co",
"http://planetx.nl/titles"
];
window.addEventListener('load', function() {
document.getElementById("rnd_link").onclick = function() {
window.open(links[Math.floor((Math.random()*3))]);
};
});
</script>
If you just want to avoid using jQuery, I suggest using window.onload to trigger the function when the page loads.
window.onload = function(){
// do stuff
};
Then in order to select a DOM element, you'll use the getElementById() method, then you'll add an event listener for a mouseclick:
document.getElementById("rnd_link").addEventListener("click", function(){
// do stuff
});
Here's the MDN entry for event listeners for further reading: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
I'd suggest this:
Call the function when the button is clicked.
<button id="rnd_link" onclick="random()"></button>
<script>
var links = [
"http://vetteletters.nl",
"http://todont.co",
"http://planetx.nl/titles"
];
function random(){
window.open(links[Math.floor((Math.random()*3))]);
}
</script>
More info for onclick here

this reference in JavaScript

Today i was writing some basic stuff of java script mean while i encountered the problem. Although i was able to sort out the problem but could not find the reason of why this were not working. Here is my code
$('document').ready(function() {
$(this).click(function() {
var node1 = $(this);
a = node1.text();
console.log(a);
});
});
In this in the console i see empty string. But if i change the $(this).click(function{...}) to $('.some_class_name').click(function{.....}); than my code works fine and display the text value of the button i clicked.
I want to know what is wrong in the above code.
You must be looking for this, Use the e.target to get the text inside of the clicked element which is present inside the document.
$('document').ready(function () {
$(this).click(function (e) {
var node1 = $(e.target);
var a = node1.text();
console.log(a);
});
});
Try this code
Just change the this keyword to body
<script type="text/javascript" src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<script type="text/javascript">
$('document').ready(function(){
$('body').click(function(){
var node1 = $(this);
a = node1.text();
console.log(a);
});
});
</script>
<body>
Test
</body>

After adding a new element in the DOM, the element does not recognize old script

I have a problem.After adding a new element in the DOM, the element does not recognize old script and the same function that was in this document, how to solve this problem? how to reload the script
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<div id='content'>Content.....</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<script src='js/script.js' type='text/javascript'></script>
</body>
</html>
// script.js //
$('#content').click(function(){
$('body').append('<div id="apended">Click me!</div>');
});
$('#apended').click(function(){
alert('click!');
});
When you use .on('click', function (e) {}) function, it works only for existing elements. To handle click event on all selector elements, even for elements which will be added in future, you can use one of these functions:
$(document).on('click', "#appended", function (e) {
// some code code
alert('click!');
});
or:
$("body").delegate("#appended", "click", function () {
// your code goes here
alert('click!');
});
For more information read article about Understanding Event Delegation
Instead of click function You can use :
1.live(old version)
2.delegate
3.on
But , if you want to use click with immutation of delegate function :
var myFn=function(e){
if(e.target.id=='apended'){
alert('click');
}
}
$(document).click(myFn)
Demo :http://jsfiddle.net/abdennour/7cyjV/

Getting the class of the element that fired an event using JQuery

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')

How to get the element that fired the "onclick" event

<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.

Categories