JS won't execute in page (works in jsfiddle) - javascript

I would first like to say that I am very new to JavaScript and Jquery, so this is hopefully a simple one,
I have some JS code to arrange the order of a few div tags which works in JSfiddle (http://jsfiddle.net/databass/Yh2L3/)
However when I try and put that into a webpage nothing happens
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Testing</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$('button').on('click', function (event) {
var divElements = $('#tours div'),
sortType = $(this).data('sort');
divElements.sort(function (a, b) {
a = $(a).data(sortType);
b = $(b).data(sortType);
// compare
if (a > b) {
return 1;
} else if (a < b) {
return -1;
} else {
return 0;
}
});
$('#tours').empty();
$.each(divElements, function (i, divElement) {
$('#tours').append(divElement.outerHTML);
});
});
</script>
</head>
<body>
<button data-sort='price'>Sort By Price</button>
<button data-sort='duration'>Sort By Duration</button>
<button data-sort='name'>Sort By Name</button>
<section id="tours">
<div class="result" data-price="749" data-duration="8" data-name="Basecamp">Info about tour 1 goes here</div>
<div class="result" data-price="2099" data-duration="19" data-name="Cycle Adventure">Info about tour 2 goes here</div>
<div class="result" data-price="1099" data-duration="25" data-name="Family Adventure">Info about tour 3 goes here</div>
<div class="result" data-price="3014" data-duration="18" data-name="Luxury Basecamp">Info about tour 4 goes here</div>
</section>
</body>
</html>
Thanks so much for your help

The javascript code you have executes before the elements being added to DOM. You need to put the javascript code just before the body ending tag or in document.ready
The handler passed to .ready() is guaranteed to be executed after the
DOM is ready, so this is usually the best place to attach all other
event handlers and run other jQuery code, jQuery docs

Related

How to add event with Javascript to an html tag

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>

Countdown clicker - JS

I'm totally lost as to where to begin here, how would I create a countdown button so that each time my button is clicked, it prints out the global variable and reduce it by 1 in the innerHTML and when it hits 0 it says BOOM?
I know I have to declare the variable outside but not sure what to do afterwards
JS:
var i = 20
function myFunction()
{
i = i--; // the value of i starting at 20
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- link to external JS file. Note that <script> has an
end </script> tag -->
<meta charset="utf-8">
<title> Task 6 </title>
<link href="style.css" type="text/css" rel="stylesheet">
<script src="task6.js" type="text/javascript"></script>
</head>
<body>
<!-- Create a paragraph with id mydata -->
<div id="box">
<p id="mydata"> Count Down </p>
<p> <button onclick="myFunction();"> Click </button></p>
</div>
</body>
</html>
I tryed this code and works fine
var i = 20;
function myFunction() {
myData = document.getElementById("mydata");
i = i - 1;
myData.textContent = i;
if(i <= 0) {//with <=0 the user if click again,after zero he sees only BOOM
myData.textContent = "BOOM!"
}
}
html code
<!DOCTYPE html>
<html lang="en">
<head>
<!-- link to external JS file. Note that <script> has an
end </script> tag -->
<meta charset="utf-8">
<title> Task 6 </title>
<link href="style.css" type="text/css" rel="stylesheet">
<script src="task6.js" type="text/javascript"></script>
</head>
<body>
<!-- Create a paragraph with id mydata -->
<div id="box">
<p id="mydata"> Count Down </p>
<p> <button onclick="myFunction();"> Click </button></p>
</div>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- link to external JS file. Note that <script> has an
end </script> tag -->
<meta charset="utf-8">
<title> Task 6 </title>
<link href="style.css" type="text/css" rel="stylesheet">
<script type="text/javascript">
var i = 20;
function myFunction() {
var myData = document.getElementById("mydata");
i = i - 1;
myData.textContent = i;
if(i <= 0) {
myData.textContent = "BOOM!"
}
}
</script>
</head>
<body>
<!-- Create a paragraph with id mydata -->
<div id="box">
<p id="mydata"> Count Down </p>
<p> <button onclick="myFunction();"> Click </button></p>
</div>
</body>
</html>
It's good practice to not inline JS in the HTML so I'll provide an extra example to show how to separate it out using a couple of DOM selection methods:
let count = 20;
// grab the element with the mydata id
const mydata = document.getElementById('mydata');
// grab the button and attach an click event listener to it -
// when the button is clicked the `handleClick` function is called
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false);
function handleClick() {
if (count === 0) {
mydata.textContent = 'Boom';
} else {
mydata.textContent = count;
}
count--;
}
<body>
<p id="mydata">Countdown</p>
<button>Click</button>
<script src="task6.js" type="text/javascript"></script>
</body>
Reference
getElementById
querySelector
addEventListener
I'll assume you want to show the variable output and the BOOM at the <p id="mydata"> Count Down </p>, if I am mistaken correct me. So, something like this:
let i = 20;
const myData = document.querySelector("#mydata");
function myFunction() {
i = i - 1;
myData.textContent = i;
if(i === 0) {
myData.textContent = "BOOM!"
}
}
You almost got it whole,only missed the textContent and if part. If this is what you wanted to achieve. If this isn't what you were looking for, hit me up so I can correct it. Cheers :)
You need some way of displaying the number inside of your variable. One of the simplist ways to do this would be to set text to your paragraph tag using getElementById() and inner HTML. For example, after running your deincrement, on the next line you would do something like...
function myFunction()
{
i = i--; // the value of i starting at 20
document.getElementById("mydata").innerHTML = i;
}
This code simply grabs your "mydata" paragraph from the DOM and injects the number into the tag as html.

Calling function from another javascript inside jquery

I have a Javascript file named loader.js which contains a function called initialize(). I want to call this function via jQuery. This is my HTML file:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="loader.js" ></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(document).on("click", ".link", function(e) {
e.preventDefault();
var a= $(this).text();
window.initialize= function{
};
initialize(a);
});
});
</script>
</head>
<body >
<h1>welcome to my website </h1>
link1
link2
<div id="main">
</div>
</body>
</html>
This is loader.js:
function initialize(a) {
$('#main').html= a;
}
I do not know what is wrong with this script, I have debug it jquery is working fine but funtion is not working correctly.
also I want that whenever the function is clicked again the div should be refreshed for example first it contain link1 but when link2 is clicked link1 should be removed inside the div how can i accomplish this task????
thanks in advance
You're not including the loader script. Add <script src='loader.js'></script> before the jQuery code.
The code in loader.js should be inside a jQuery(document).ready callback since it's now using jquery (the html method).
Also as #jiihoo pointed out you should use $('#main').html(a); instead of $('#main').html = a;.
You should change to code of loader.js to this.
function initialize(a) {
$('#main').html(a);
}
Heres the whole thing you could do.
Html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script>
<script src="loader.js"></script>
</head>
<body >
<h1>welcome to my website </h1>
link1
link2
<div id="main"></div>
</body>
</html>
Loader.js
jQuery(document).ready(function() {
jQuery(document).on("click", ".link", function(e) {
e.preventDefault();
var a = $(this).text();
initialize(a);
});
});
function initialize(a) {
$('#main').html(a);
}

click event not happening with bootstrap panel

I'm trying to make my own class with panels that open and close content using Bootstrap and jQuery (not an accordion, I want multiple open at a time). However, the click event isn't working for me and I have no idea why... I tried the "*" selector and the alert was working but it's not working when I try to associate it with specific elements.
Practice2.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Practice 2</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="../static/css/prism.css">
<link rel="stylesheet" href="../static/css/styles.css">
<script src="../static/js/prism.js"></script>
<script src="../static/js/script.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="panel panel-default panel-toggle" id="demo">
<div class="panel-heading">solution</div>
<div class="panel-body">
<code class="language-python">
def solution(self):
func = self.functionGenerator()
length = self.endTime - self.initialTime
timesConcerned = [self.initialTime+x/1000. for x in range(length*1000)]
return odeint(func,self.initialValues,timesConcerned)
</code><br>
Explanation
</div>
</div>
</div>
</body>
</html>
script.js
// $(".panel-toggle:panel-header").click(function(){
// // $(this).next().toggle();
// alert("hello");
// });
$("#demo").click(function(){
alert("hello");
});
styles.css
.panel-toggle .panel-heading:after {
font-family:'Glyphicons Halflings';
content:"\e114";
float: right;
color: grey;
}
.panel-toggle .collapsed:after {
content:"\e080";
}
.panel-toggle .panel-body {
}
Clearly the rest of the code needs some adjustment but I'm just troubleshooting this part right now and would appreciate some advice on what I'm missing. Thanks!
With
HTML
<div class="panel panel-default panel-toggle">
<div class="panel-heading">solution</div>
<div class="panel-body">
<code class="language-python">
def solution(self):
func = self.functionGenerator()
length = self.endTime - self.initialTime
timesConcerned = [self.initialTime+x/1000. for x in range(length*1000)]
return odeint(func,self.initialValues,timesConcerned)
</code>
Explanation
</div>
</div>
JS
$(document).ready(function(){
$(".panel-heading").click(function(){
$(this).next().toggle("slow");
});
});
works
JSFiddle demo
You should put your jQuery code in document.ready block ensure your code working after those element been generated.
Script.js should be changed like this.
$(document).ready(function(){
$("#demo").click(function(){
alert("hello");
});
});

addEventListner working only at app creation

For some reason my eventHandling code stopped working.
I was working on some functions to handle the indexedDB stuff, when i went back to work on the interface, i noticed that the eventHandlers only worked at app creation, even when i didnt performed any action on them, they just go off.
Heres my default.js
(function () {
"use strict";
WinJS.Binding.optimizeBindingReferences = true;
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var _swAlarm;
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
} else {
}
args.setPromise(WinJS.UI.processAll());
}
};
app.oncheckpoint = function (args) {
};
function testSelection(value) {
console.log("from event listner "+value)
}
function getDomElements() {
_swAlarm = document.getElementById("swAlarm");
}
function registerHandlers() {
_swAlarm.addEventListener("onchange", console.log("ola"));
}
app.onready = function () {
getDomElements();
registerHandlers();
}
app.start();
And this is my default.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>MyApp</title>
<!-- WinJS references -->
<link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
<script src="//Microsoft.WinJS.1.0/js/base.js"></script>
<script src="//Microsoft.WinJS.1.0/js/ui.js"></script>
<!-- my references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
<script src="/js/database.js"></script>
<!-- jquery references -->
<script src="js/jquery-1.8.2-win8-1.0.js"></script>
<script src="js/visualize.jQuery.js"></script>
<script type="text/javascript"> jQuery.isUnsafe = true;</script>
<link href="/css/default.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="content">
<div id="settings">
<h2 id="lAlarm">Alarm</h2>
<div id="swAlarm" data-win-control="WinJS.UI.ToggleSwitch" ></div>
<input id="iMaxval" type="number">
<input id="iMinval" type="number">
<button id="bSave">Save</button>
</div>
<div id="graph">
<h2 id="hGraph" class="graph">Graph</h2>
</div>
<div id="stats">
<h2 id="hStats" class="stats">Stats</h2>
</div>
</div>
</body>
</html>
When you run this code:
_swAlarm.addEventListener("onchange", console.log("ola"));
you are:
running console.log("ola")
affecting the result as a callback for the event onchange of _swAlarm.
This is wrong on many levels.
console.log("ola") does not return a call back. I think I understand what you meant, and the correct code could be: function() { console.log("ola"); }
When using addEventListener you have to use dom lexique with event denomination. In your case, onchange needs to be instead change. If you had to affect this event directly in html, you indeed would have to use onchange="console.log("ola");". But not with addEventListener.
The final result is:
_swAlarm.addEventListener("change", function() { console.log("ola"); }, false);
As for why was it working on app creation, I think it is simply because on app creation console.log("ola") was called right away at event affectation, but since no event was actually affected later on you would not get any result for the onchange event.
On a side note, and since I guess you're sort of migrating from "old" syntaxis (onchange... etc.) to the addEventListener api, I'll add an important difference between the 2 modes: when an event is executed the old way, this referers to window. But affecting the callback through addEventListener makes the domElement itself (_swAlarm in your case) be the target of this during the callback execution.

Categories

Resources