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') };
Related
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>
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
using javascript, is there a condition something like this
if (clicked===true && var===3) {
function executes here
}
if there isn't, how can you get the same effect?
For mouse and UI handling the Javascript model is based on events. In other words what you do is
element.onclick = function() {
// what to do when that element is clicked
};
for example:
<!DOCTYPE html>
<html>
<body>
<div id="thediv">Click me</div>
<script>
document.getElementById("thediv").onclick = function() {
alert("Awww... why did you do that?");
};
</script>
</body>
</html>
you have to bind an eventhandler to the element. you can do this inline with an onclick eventhandler. Also you can't use the name var because it is a reserved word in javascript.
html
<a id="mylink" href="#" onclick="handleMyClick();">Click me</a>
javascript
var myvar=3;
handleMyClick(){
if(myvar==3){
alert("you clicked the link and myvar is 3");
}
}
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;
});
});
I am trying out this simple code. What I want is that when a paste event is fired on the second input textbox, it should be cleared, after copying its contents, removing the readonly attribute of the previous textbox, and pasting it there. however, nothing is happening.
The paste event is fired alright, because if I replace the code in the timer by a simple alert, it works. Can anyone tell me what's wrong here?
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$(".boo").bind("input paste",function() {
elem = this;
setTimeout(function() {
$(".foo").removeAttr("readonly");
$(".foo").text($(elem).text());
$(elem).text("");
},100);
});
});
</script>
</head>
<body>
<input class = 'foo' type = 'text' /><input class = 'boo' type = 'text' />
</body>
</html>
First of all, you should use .val() instead of .text() with input control.
$(document).ready(function () {
$("input.boo").bind("paste", function () { //also changed the binding too
var elem = $(this);
setTimeout(function () {
$(".foo").val(elem.val());
elem.val("");
}, 100);
});
});
Also, your bound event(s) were fired twice when text is pasted in the control. That's because, you have bound both input and paste events to the element(s) with "boo" class.
So here, instead of:
$(".boo").bind("input paste", function() {});
Use this:
$("input.boo").bind("paste", function() {});
This will bind only the paste event to input elements with "boo" class.
See updated jsFiddle example.