This question already has answers here:
Calling functions with setTimeout()
(6 answers)
Closed 6 years ago.
I'm having issues using Javascript to run a function. What I want to happen is I want the function to fire off when the user clicks a button. However, it fires off when the page loads.
Here is the entire code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<input type="submit" id="btn" value="Load">
<div id="description">
<div id="info">
<h1 id="title"></h1>
<p id="description"></p>
<ul id="list"></ul>
</div>
</div>
</div>
<div class="col-md-2"></div>
</div>
</div>
<script>
var btn = document.getElementById('btn');
var title = document.getElementById('title');
var description = document.getElementById('description');
var list = document.getElementById('list');
btn.onclick = load();
function load() {
alert("Working.");
}
</script>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
Right now, it obviously doesn't do much except fire off an alert box. But I'll by using it to load in a file via XMLHttpRequest object later. But right now, its not working the way it should.
I should also point out that the code works fine with an anonymous function, But the whole idea is to have a normal function. I'm just not sure why it would work with an anonymous function and not a normal one.
It should be
var btn = document.getElementById('btn');
var title = document.getElementById('title');
var description = document.getElementById('description');
var list = document.getElementById('list');
btn.onclick = load;
function load() {
alert("Working.");
}
DEMO
Related
I've a landingpage with dynamic html tags.
The Problem is, that i can't select directly the tag. Its a link.
the following code is the construct:
<div id="testid"><div><div>Button 1<div><div><div>
Every time someone clicks on the link (a-tag) I want to fire an event like the following code:
Button 1
the question: what is the Javascript code to add the onclick="dataLayer.push({'event': 'button1-click'}) attribute to the a tag.
I tried the following code:
var d = document.getElementById("testid").firstchild;
d.setAttribute("onclick", "dataLayer.push({'event': 'button1-click'})");
but it seems to the code is incorrect. The a tag is also not the first child; there are 2 divs between :(
Use querySelector and addEventListener:
document.addEventListener('DOMContentLoaded', function () {
var dataLayer = [];
var d = document.querySelector("#testid a[name=button1]");
d.addEventListener("click", function () {
dataLayer.push({ 'event': 'button1-click' });
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="testid">
<div>
<div>
Button 1
<div>
<div>
<div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="script.js">
</script>
</body>
</html>
There's a few things you were missing from your JS.
Using a more specific selector (#testid a[name=button1] vs. the firstchild of #testid, which was not accurate).
Wrapping all the code in a DOMContentLoaded listener. JS that depends on elements on a page needs to wait for the page to build first, that's what DOMContentLoaded is.
Check out my solution. Hope this helps.
var d = document.querySelector("#testid a");
var dataLayer = []
d.onclick = function () {
dataLayer.push({'event': 'button1-click'})
console.log(dataLayer.length)
}
<div id="testid"><div><div>Button 1<div><div><div>
I'm trying to improve my Javascript by starting a simple web interface, but every time I try to add an event listener to an input field, it breaks my code.
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="colors.css">
<script src="spot.js"></script>
</head>
<div id="ask">
Search for an artist to see their top songs:
</div>
<form>
<input type="text" name="artist" id="artist-search">
</form>
<div id="sub">
submit
</div>
</html>
And here's my Javascript:
window.onload = loaded;
var inField;
function loaded() {
document.getElementById("sub").addEventListener("click", search);
inField = document.getElementById("artist-search");
}
//https://api.spotify.com/v1/search?q=tania%20bowra&type=artist
function search() {
alert();
//var query = "//https://api.spotify.com/v1/search?q=";
}
When I add the getElementById to "artist-search", the alert in the search function stops working. Why is this? And is there a better way to get the text in an input field when someone clicks a submit button using vanilla Javascript?
This is driving me nuts. I have put the html and javaScript code below. Whenever I refresh my page I get Uncaught TypeError: screen.addEventListener is not a function. I insert any other variable or ID for screen and it works fine.
HTML Code
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Calculator</title>
<link rel="stylesheet" href="css/reset/reset.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="calculator">
<div id="screen">
</div>
<div id="layout">
<ul id="first-row" class="btn-row">
<li><button>C</button></li>
<li><button>=</button></li>
</ul>
<ul id="sec-row" class="btn-row">
<li><button>7</button></li>
<li><button>8</button></li>
<li><button>9</button></li>
<li><button>+</button></li>
</ul>
<ul id="third-row" class="btn-row">
<li><button>4</button></li>
<li><button>5</button></li>
<li><button>6</button></li>
<li><button>-</button></li>
</ul>
<ul id="fourth-row" class="btn-row">
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
<li><button>*</button></li>
</ul>
<ul id="fifth-row" class="btn-row">
<li><button>0</button></li>
<li><button>/</button></li>
</ul>
</div>
</div>
<script src="js/app.js">
</script>
</body>
</html>
JavaScript Code
var screen = document.getElementById('screen');
var btn = document.getElementsByTagName('button');
var clear = btn[0];
var equals = btn[1];
var seven = btn[2];
clear.addEventListener('click', here);
screen.addEventListener('click', function(){
alert('wth');
});
You have a naming issue. It is clashing with the window.screen object
console.log(window.screen);
MDN window.screen
Rename the variable to something else and it works fine.
var screenX = document.getElementById("screen");
screenX.addEventListener("click", function() { alert("x"); });
<div id="screen">Click</div>
or take it out of global scope
(function () {
var screen = document.getElementById("screen");
screen.addEventListener("click", function() { alert("x"); });
}());
<div id="screen">Click</div>
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm very new to JavaScript. Here is my html page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<header>
<h1>This is my site!</h1>
</header>
<section>
<h2>My site content</h2>
<input type="text" id="name">
<button id="addName">Submit</button>
<hr>
<p>name</p>
</section>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
var myName = $("#name").val();
$("#addName").click(showName(myName));
function showName(value) {
$("p").html(value);
};
</script>
</body>
</html>
I want to type something in the textfield and click the submit button to change text in the <p>. But It doesn't work the way I want. What am I doing wrong?
Sorry for my bad English.
in your setup, myName is only evaluated once (empty string). You need to grab the value each time you perform the addName click action:
$("#addName").click( function(event) {
showName($("#name").val());
});
function showName(value) {
$("p").html(value);
};
The Solution:
function showName() {
var myName = $("#name").val();
$("p").html(myName);
}
$("#addName").click(function () {
showName();
});
Your Mistakes
var myName = $("#name").val(); //myName will get blank value. Its doesn't matter you click or not.. it will be always blank.
$("#addName").click(showName(myName)); // Not a proper syntax to run a function after click.
function showName(value) {$("p").html(value);} //Your function will run without click. Because you mentioned this 'Run' function in click syntax directly.
Everything put together: http://jsfiddle.net/5fqauk6L/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<header>
<h1>This is my site!</h1>
</header>
<section>
<h2>My site content</h2>
<input type="text" id="nameInput">
<button id="addName">Submit</button>
<hr>
<p id="name">name</p>
</section>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$("#addName").click(function(){
var myName = $("#nameInput").val();
$("#name").html(myName);
});
</script>
</body>
</html>
Side note: you should really work on indenting your stuff. I left it without indentation so you could understand it how you wrote it.
JS :
<script>
$("#addName").click(function(){
var myName = $("#name").val();
$("p").html(myName);
});
</script>
This question already has an answer here:
Jquery Event Not Triggering for DOM Elements Created after page load [duplicate]
(1 answer)
Closed 8 years ago.
few of div elements are generated using ajax and few are static. The jquery is working only on static elements not on dynamic generated html. I am running a jquery on clicking any element of "app" class. But the jquery is only working on static html not on the dynamically html
<!Doctype html>
<html>
<head>
<title>applications</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="//code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
type:'GET',
url:'application/show_app.php',
data:{show_app:"1"},
success: function(data){
if(data)
{
var split= data.split('%%%%');
for(var i=0;i<split.length-1;i++)
{
var div= document.createElement("div");
var div_child=document.getElementById("app_row").appendChild(div);
div_child.className="app";
div_child.innerHTML="dynamic"; //dynamically generated
}
}
},
failure: function(){
alert(failed);
}
}) ;
$(".app").click(function(){
alert("jquery"); //jquery which will run on clicking the division
});
});
</script>
</head>
<body id="default" class="full"> //basic html
<div class="header">
<h1>
<a title="urban airship">urbanairship</a>
</h1>
</div>
<div class="main" name="application-main">
<div class="sub-header">
<h2>Your Applications</h2>
<div class="sub-header-actions">
<a href="application/add_app.php/">
<span class="sprite plus-ico"></span>
New App
</a>
</div>
</div>
<div class="row main-app-list" id="app_row">
<div class="app">static</div> //static html
</div>
</div>
</body>
</html>
Try:
$(document).on('click', '.app' , function(){
alert("jquery"); //jquery which will run on clicking the division
});
This works because your event listener is now attached to the document and not the individual elements. This allows elements that are loaded in via AJAX to still fire events. You should also look at scoping the on i.e. $("#myWrapper").on(...) as this is better for performance.
See documentation: JQuery On