Javascript: onclick function to get elements - javascript

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/

Related

How do i use javascript to manipulate empty divs?

So this is what i want to do. if my div doesn't contain anything a js file will write "no links check in the future."
my html file:
<div id="games" load="checknull(this)"></div>
my js file:
function checknull(id) {
gamelist = document.getElementById(id);
if (gamelist.innerHTML == null) {
gamelist.innerHTML = "No links check in the future"
}
}
But it doesn't work! I've linked the external js file correctly its name and the tag!
There is no load event on a div.
You can achieve the result you're looking for with the onload event of either body or window depending on the rest of your code:
<body onload="checknull(this)">
</body>
I tried this and works for me:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>empty div</title>
</head>
<body>
<div id="games"></div>
<script>
gameList = document.getElementById("games");
window.onload = function () {
if (!gameList.innerHTML) {
return (gameList.innerText = "No links check in the future");
}
};
</script>
</body>
</html>
There is two things that will not work. load handle doesn't exist on div so you could use window.onload and your condition "gamelist.innerHTML == null" will always be false you should use gamelist.innerHTML == "".
First of all, divs don't have event "load", so if you want to wait until the DOM is loaded use document.addEventListener("DOMContentLoaded", callback) instead.
Also, innerHTML and innerText either are strings, not null.
document.addEventListener("DOMContentLoaded", () => {
gamelist = document.getElementById("games");
if (!gamelist.innerHTML) {
gamelist.innerHTML = "No links check in the future"
}
});
<div id="games" load="checknull(this)"></div>

Javascript Execute onclick event stored in variable

I've created the function below to identify an onclick event which is dynamically generated with each page load. I'm able to get the onclick event into a variable (developer console output shown below). I want to execute that onclick event but can't find a good way of doing that. Any assistance is appreciated.
"ƒ onclick(event) {
mstrmojo.dom.captureDomEvent('*lK1129*kWA92AF1C396244F28902B3171F9642E57*x1*t1530820506700','click', self, event)
}"
function applyAll() {
//Get the self Link to click it
var linkBys = document.getElementsByClassName("mstrmojo-DocTextfield-valueNode");
// loop through each result
for(y = 0;y < linkBys.length;y++){
// retrieve the current result from the variable
var linkBy = linkBys[y];
// check the condition that tells me this is the one I'm looking for
if(linkBy.innerText.indexOf("link") !== -1){
// Find the right class
var idy = document.getElementsByClassName("mstrmojo-DocTextfield-valueNode")[y].onclick;
console.log(idy);
}
}
}
If the property 'onclick' is defined as a function, you can just run it as a function.
var idy = document.getElementsByClassName("")[y].onclick();
You could also handle it another way:
var idy = document.getElementsByClassName("")[y].onclick;
idy();
onclick is not an event, it's a function which gets executed when element is clicked. If you want to simulate click you can do element.click()
If you used:
element.addEventListener('click',()=>...);
instead of:
element.onclick=()=>...
then all you have to do is:
document.getElementsByClassName("mstrmojo-DocTextfield-valueNode")[y].dispatchEvent(new Event('click'));
You can call the function returned , adding parens:
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function foo() {
var idy = document.getElementsByClassName("mstrmojo-DocTextfield-valueNode")[0].onclick;
console.log(idy);
idy();//like so
}
function alertMe() {
alert('Hello');
}
</script>
</head>
<body>
<button id="btn" class="mstrmojo-DocTextfield-valueNode" onclick="alertMe();">No click</button>
<button id="btn2" onclick="foo()">Click me</button>
</body>
</html>

Onclick button doesn't function

i try to create a button when the page is load.
<!DOCTYPE html>
<html>
<head>
<script>
function createButton(){
var newButton = document.createElement("button");
newButton.onclick="document.write('Tasto premuto')";
var textButton = document.createTextNode("Premi qui");
newButton.appendChild(textButton);
document.body.appendChild(newButton);
}
</script>
</head>
<body onload="createButton()">
</body>
</html>
the button is created succesfully, but the function that I have associated with onClick event doesn't work. any ideas?
onclick expects a function, not a string:
newButton.onclick = function() { document.write('Tasto premuto') };
Please see this jsFiddle
Of course, you should be aware that document.write() completely clears the DOM of all current content, rather than simply appending the string to the existing content.
You're assigning a string to function pointer:
Change:
newButton.onclick="document.write('Tasto premuto')";
To:
newButton.onclick= function(){ document.write('Tasto premuto') };

Javascript: Eventhandler not functioning, works in JSFiddle

So this is an answer to another question I posted and I think it is the correct solution. However, while it works wonderfully in jsfiddle it does not function whatsoever outside of that environment. I have tried multiple combinations and I cannot get this thing to work right.
I've tried onLoad in the body, Window.onload both in the header wrapping around the function and separately calling it at the base of the page after all the elements have loaded. Nothing works.
I always get this issue:
Uncaught TypeError: Cannot call method 'addEventListener' of null
Which is frustrating, because all other solutions to this error I have seen revolve around ensuring you do in fact have the specified ID the handler triggers off of in your HTML. Which I do.
I know its probably overkill to make a post here on this but I'm yanking my hair out.
Here's the JSfiddle: http://jsfiddle.net/fFW5r/1/
Here's a mockup page I made to test the concept (which never works):
<!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 type="text/javascript">
var link_container = document.getElementById('links');
function myFunction(){ link_container.addEventListener('click', function(e){
if(e.target.nodeName === "A"){
var href = e.target.getAttribute('href'),
selfhost = window.location.hostname;
if(href.indexOf(selfhost) !== -1){
alert('Inbound link clicked');
} else {
alert('Outbound link clicked');
}
}
}, false);
}
</script>
</head>
<body onload="myFunction()">
<div id="links">
Inbound Link
Outbout Link
</div>
<script>window.onload=myFunction()</script>
</body>
</html>
This particular iteration I was trying to test it with the onload call at the bottom of the page after everything had loaded.
var link_container = document.getElementById('links'); need to be executed on document.onload so it has to be inside myFunction
In jsfiddle, the code is executed on load by default. in the fiddle at the left side panel > second select box if you select no wrap - in head you can recreate the problem.
Demo: Fiddle
<script type="text/javascript">
function myFunction(){
var link_container = document.getElementById('links'); // <<-- Move it inside `myFunction()`
link_container.addEventListener('click', function(e){
if(e.target.nodeName === "A"){
var href = e.target.getAttribute('href'),
selfhost = window.location.hostname;
if(href.indexOf(selfhost) !== -1){
alert('Inbound link clicked');
} else {
alert('Outbound link clicked');
}
}
}, false);
}
</script>
The reason it doesn't work is that you are initializing link_container before the DOM is ready. Then when myFunction() runs, link_container has been initialized to undefined. Which causes it to fail. Initializing it in the function (after the DOM has loaded) should fix the issue
Put declare link_container inside the function.
var link_container = document.getElementById('links');
function myFunction(){
link_container.addEventListener('click', function(e){
if(e.target.nodeName === "A"){
var href = e.target.getAttribute('href'),
selfhost = window.location.hostname;
if(href.indexOf(selfhost) !== -1){
alert('Inbound link clicked');
} else {
alert('Outbound link clicked');
}
}
}, false);
}

Identify which element id or class was clicked using jQuery?

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.

Categories