Calling Javascript function from a div - javascript

Can I please have some help to call a function that is created in Javascript when a reference is made to a DIV in HTML.
Here is my function:
function testFunction()
{
alert("Test");
}
I would like the testFunction to be called when the following reference is made in HTML:
<div id="testFunction">
Can I please have some help to do this?

You can attach the call to a click handler:
In markup:
<div id="testFunction" onclick="testFunction()">
Or inside your script block:
function testFunction() {
alert("Test");
}
var el = document.getElementById("testFunction");
el.onclick = testFunction;

Related

Function is not accessible after onload event. "TypeError: {someFunctionName} is not a function"

I have written a small and simple slider with Javascript. Because I want to be sure that the slider works when I load the javascript in the footer of the page. I added an onload event and copied the whole slider application inside the event. In the HTML I unfortunately have an inline onclick element in a tag. But since I have the code inside the onload scope the onclick doesn't work anymore. My idea is not to bind the event inline in the html but directly in the javascript. That should work. But I am also interested if it is possible to do it with the inline onclick.
Question What do I have to do so that the onclick element addresses the corresponding function within the onclick function?
document.querySelector('body').onload = function() {
function init() {
// ...
}
const f2 = function() {
// ...
}
init();
/* that will work */
const anchorPrev = document.querySelector('.prev');
anchorPrev.addEventListener('click', () => {
console.log('prev');
});
/* My question */
function next() {
console.log('next')
}
};
a {
cursor: pointer;
}
<body>
<a class="next" onclick="next()">next (I'm curious to know if it works!?)</a><br/>
<a class="prev">prev (Will work)</a>
</body>
Two issues:
It's better to wait for the DOMContentLoaded event on the window object.
You're defining the function within the scope of the function, so it's not globally accessible. This means that the onclick can't see the function. Use a let variable, then set the function inside the listener callback like this:
<button onclick="log()">click me</button>
<script>
let log;
window.addEventListener('DOMContentLoaded', () => {
console.log('loaded');
log = () => console.log('clicked');
});
</script>
You can add that the onload event = function next()
JavaSript code:
document.querySelector('body').onload = function() {
const a = document.querySelector('a')
a.onclick = function next() {
event.preventDefault()
console.log('next')
}
};

oninput isn't calling the function

I'm trying to run a function whenever an input's text changes. I'm using the oninput attribute to do that. I followed W3Schools tutorial. When I try it on in my own code, (or JSFiddle,) the function doesn't get called.
JSFiddle
$(document).ready(function () {
function myFunction() {
alert("asdf");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myInput" oninput="myFunction()">
Because oninput calling a method myFunction that is out of scope. There is no reason for it to be inside the ready handler
//$(document).ready(function () { <--get rid of this
function myFunction() {
alert("asdf");
}
//}); <-- get rid of this
Now it will work

HTML onload not working

I'm attempting to use html onload event to trigger javascript, but is not working. The original code was:
html:
<div id='map' onload="generateMap.createMap();"></div>
JS:
var generateMap = function(){
return{
createMap: function(){
console.log(this.attr('id'));
element = this.attr('id');
navigator.geolocation.getCurrentPosition(initialize);
}
};
}
In an attempt to test, I changed the html to:
<div id='map' onload="alert('test');"></div>
Can anyone tell me why nothing is working?
First, the onload attribute is not valid for a div tag. You most likely intended to place the onload in the body tag.
Unfortunately, that's not the only problem.
In your onLoad you are referencing generateMap as if it is an object with method createMap. However, this is not the case. You have assigned generateMap to an anonymous function.
To get your code working, generateMap needs to be an object with method createMap.
You just need to set it as an object in the first place:
var generateMap = {
createMap: function(){
console.log(this.attr('id'));
element = this.attr('id');
navigator.geolocation.getCurrentPosition(initialize);
}
};
Or if you need to retain the anonymous function for whatever reason, you can use an immediately executing function:
var generateMap = (function(){
return {
createMap: function(){
console.log(this.attr('id'));
element = this.attr('id');
navigator.geolocation.getCurrentPosition(initialize);
}
})();
There is no onload event for a div. You can use the script tag just after the div tag to emulate onload behavior.
Use this
<head>
<meta charset="utf-8">
<script type="text/javascript">
var generateMap = {
createMap: function(element) {
navigator.geolocation.getCurrentPosition(initialize);
}
};
</script>
</head>
<body>
<div id='map'></div>
<script type="text/javascript">
generateMap.createMap('map');
</script>
</body>
Assuming Chrome.. div tags do not have an onload event. Check the following two jsfiddles:
Does not work:
http://jsfiddle.net/o81e4dkr/
Works:
http://jsfiddle.net/p3osqrdn/
I do not know of a way to have an event fired when a div is loaded, unless it is being loaded in via jQuery.load(), in which case you can use the callbacks.
If you're using jQuery then I like the following function which adds onload capability to all tags:
$(document).ready (function () {
jQuery.each ($("[onload]"), function (index, item) {
$(item).prop ("onload").call (item);
return false;
});
});

Click a button element on page load

I'm trying to auto-click a button to initiate a function when the html page loads. I've tried document.getElementById('watchButton').click and it doesn't seem to work, the button is not clicked. Any suggestions?
<div class="content">
<div class="action-area ch30">
<button class="button dh" id="watchButton">Start Geolocation Watch</button>
<button class="button dh" id="refreshButton" >Refresh Geolocation</button>
</div>
The javascript:
run:function() {
var that = this;
document.getElementById("watchButton").addEventListener("click", function() {
that._handleWatch.apply(that, arguments);
}, false);
document.getElementById("refreshButton").addEventListener("click", function() {
that._handleRefresh.apply(that, arguments);
}, false);
},
Thanks!
I'd put it inside document.ready (so it doesn't fire until the DOM loads) and use jQuery syntax:
$(function() {
$('#watchButton').click();
});
http://jsfiddle.net/isherwood/kVJVe/
Here's the same fiddle using jQuery syntax: http://jsfiddle.net/isherwood/kVJVe/4
That said, why not just name your function and call it directly?
It would be click() not click
document.getElementById("watchButton").click();
You would need to call it onload or after the function has run
window.onload = function () {
document.getElementById("watchButton").click(); };
Try this ^^
try trigger
<script>
$(document).ready(function() {
$("#watchButton").trigger('click');
});
</script>
document.getElementById("studyOne").click();
$("#studyOne").trigger('click');
Put this in onload function. It worked for me.

Why does the onclick fire next function not assigned to it?

Why clicking the button fires the alert? It is assigned to the paragraph, not button.
HTML:
<button onclick="foo()">Click me</button>
<p id="hidden" style="display:none"> I was hidden </p>
Javascript:
function foo(){
document.getElementById("hidden").style.display = "block";
document.getElementById("hidden").onclick = innnerClick();
}
function innnerClick(){
alert("Ouch! That hurt!")
}
Because of this line:
// ----------------------------------------------------vv
document.getElementById("hidden").onclick = innnerClick();
Here you call the innnerClick function immediately.
Just remove () after to pass the reference to a function instead of calling it, i.e.
document.getElementById("hidden").onclick = innnerClick;
Since, you need to add the reference of the function like this:
function foo(){
document.getElementById("hidden").style.display = "block";
document.getElementById("hidden").onclick = innnerClick;
}
not directly calling it.
Fiddle Demo
In jQuery, we can reproduce the same issue like:
$('button').click(function () {
$('#hidden').show();
$('#hidden').click(innnerClick()); <-- see the function with () here
});
Fiddle Demo
The issue is same here, we just need to pass the function reference to click handler here like:-
$('#hidden').click(innnerClick);
Fiddle Demo

Categories