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.
Related
Can someone please help me out with why my event handler on lines 36-37 of my code and why that is not working?
Here is my event handler here that is giving me problems which can also be found in my code below. I'm a rookie trying to learn this stuff. I think once I can get this figured out I can figure out how to use the event bubbling. Appreciate the help in advance!
$('.done-item').on('click', () => {
console.log('This task is completed');
})
JS and Jquery
//jQuery DOM Variables
$(() => {
const $inputBox = $('#input-box');
const $addButton = $('#submit');
const $things2Do = $('#to-do-list');
const $done = $('#completed');
// Functions
const toDoFunction = () => {
const $newToDo = $('<h3>').addClass('to-do-item').text($inputBox.val());
const $completedButton = $('<button>').addClass('done-item').text('COMPLETED');
$newToDo.append($completedButton);
$things2Do.append($newToDo);
resetInputBoxFunction();
}
const resetInputBoxFunction = () => {
$inputBox.val('');
}
const completedFunction = () => {
}
//Event Handlers
$addButton.on('click', toDoFunction); // add To Do item by clicking on ADD button
$($inputBox).keypress(() => { //Event handler to add To Do's when enter button is pressed
if(event.key === 'Enter'){
toDoFunction();
}
})
**//THIS EVENT HANDLER IS NOT WORKING. WHY???**
$('.done-item').on('click', () => {
console.log('This task is completed');
})
}) // end of the onload jQuery function
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>To Do App</title>
<!-- CSS stylesheet -->
<link rel="stylesheet" href="main.css">
<!-- remember, jQuery must come first -->
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<!-- now your code -->
<script src="app.js" charset="utf-8"></script>
</head>
<body>
<div id="container">
<h1>What to Do</h1>
<div id="input-container">
<!-- input and input button -->
<label for="input-box"></label>
<input type="text" name="" value="" id="input-box">
<button type="button" name="button" id="submit">ADD</button>
</div>
<!-- Container for both lists -->
<div id="lists">
<!-- left list, things added should have a class of `to-do-item` to get the css -->
<div id="to-do-list">
<h2>Things to Do</h2>
</div>
<!-- right list, things added should have a class of `completed` -->
<div id="completed">
<h2>Things That are Done</h2>
</div>
</div>
</div>
</body>
</html>
This is how it will work:
$(document).on('click', '.done-item', () => {
console.log('This task is completed');
})
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 have tried: inside the for loop, inside the .done function but outside the for loop, and before and after the button function end. I'm wanting to be able to run a function on the click of the giphyImage.
Below is the code I am trying to insert somewhere to get the second click and test it in the console but nothing displays in the console at all.
$('giphyImage').on('click', function() {
console.log('testclickedimage')
});
Here is my HTML:
<!-- language: lang-html -->
<!DOCTYPE html>
<html>
<head>
<!--Megatags-->
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--Title on browser tab-->
<title>Bradley's Giphy API App</title>
<!--Reset tag-->
<link rel="stylesheet" href="assets/css/reset.css">
<!--Bootstrap tag-->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!--Css tag (after bootstrap)-->
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="container">
<div class="buttons">
<button data-giphy="cat">Cats</button>
<button data-giphy="dog">Dogs</button>
<button data-giphy="bird">Birds</button>
<button data-giphy="horse">Horses</button>
<button data-giphy="parrots">Parrots</button>
<button data-giphy="jason schwartzman">Jason Schwartzman</button>
<button data-giphy="zooey deschanel">Zooey Deschanel</button>
<button data-giphy="michael cera">Michael Cera</button>
<button data-giphy="zach braff">Zach Braff</button>
<button data-giphy="natalie portman">Natalie Portman</button>
<button data-giphy="pizza">Pizza</button>
<button data-giphy="hamburger">Hamburger</button>
<button data-giphy="beer">Beer</button>
<button data-giphy="shrimp">Shimp</button>
<button data-giphy="lobster">Lobster</button>
</div>
<div class="addButtons"></div>
<div class="gifsAppearHere"></div>
</div>
<!--Jquery tag-->
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<!--Javascript tag-->
<script src="assets/javascript/game.js"></script>
</body>
</html>
Here is my javascript code:
$('button').on('click', function() {
var giphy = $(this).data('giphy');
var queryURL = "http://api.giphy.com/v1/gifs/search?q=" + giphy
+ "&api_key=dc6zaTOxFJmzC&limit=10";
//testing variable
console.log (queryURL);
$.ajax({
url: queryURL,
method: 'GET'
}).done(function(response) { //done function
//console logs results remove when done testing
console.log(response)
//pulls response from data key
var results = response.data
//loops though images randomly
for (var i = 0; i < results.length; i++) {
//creates Div
var giphyDiv = $('<div class="giphyDiv">');
//pulls ratings
var p = $('<p>').text('Ratings: ' + results[i].rating);
//creats images
var giphyImage = $('<img>');
//pulls images from API
giphyImage.attr('src', results[i].images.fixed_height.url);
//appends rating and image
giphyDiv.append(p);
giphyDiv.append(giphyImage);
//prepends to class specified in html
$('.gifsAppearHere').prepend(giphyDiv);
} //end of for loop
}); //end of done function
}); //end of button function
::edit:: was able to fix by targeting 'img' instead of 'giphyImage'
$('img').on('click', function() {
console.log('testclickedimage')
});
now console displays 'testclickedimage'
I think your problem is that giphyImage is a string and not a DOM element. That's why you cannot attach an event listener to it.
Try this:
var giphyImage = document.createElement('img');
giphyImage.setAttribute('src', yourImageSource);
giphyImage.addEventListener('click', yourFunctionHere /* without () */);
giphyDiv.appendChild(giphyImage);
Edit
A better way to achieve the same result is to use event delegation.
In short, instead of attaching one event listener to each image element, you can simply attach a single event listener to a parent element, which will fire for all children matching some criteria (for example, a class name). Even better, it does not matter at all if the child already exists or is added at a later time.
Example using pure JavaScript:
var body = document.querySelector('body');
body.addEventListener('click', function(event) {
if (event.target.tagName === 'IMG')
youFunctionHere();
})
I have a textarea and a span. The textarea has an ngBlur which calls a function. I only want that function to run its code when the cause of the blur wasn't a click on the span. How can I do that?
http://plnkr.co/edit/ENvuujbychxYum1EMmkf?p=preview
HTML
<!DOCTYPE html>
<html ng-app='app'>
<head>
<script data-require="angular.js#1.4.7" data-semver="1.4.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller='MainController as vm'>
<textarea ng-blur='vm.selective()'></textarea>
<span>span</span>
</body>
</html>
JS
angular
.module('app', [])
.controller('MainController', MainController)
;
function MainController() {
vm.focus = true;
vm.onBlur = function() {
// HOW DO I DO THIS?
// if (spanIsClicked) {
// return;
// }
vm.focus = false;
};
}
I believe you can pass in the DOM element as an argument in angular, looking like :
vm.onBlur = function($event){}
You could then access the event by using event.target. I know this works with ng-click so I'm not totally positive if the same rules apply for ng-blur.
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