Class attribute missing from DOM in inspector - html

I'm using a function to try and select a div with a class attribute that is nested in a div with an ID. The function does nothing and after some debugging it turns out that when I inspect element in my browser, the div is not showing a class even though I have a class in my HTML. Because there's no class the function doesn't know what to select. See in the following code function playBall is calling function countDown which should be selecting div.timer.
<!DOCTYPE html>
<html>
<head>
<title>Home Run Derby (CSCI2447)</title>
<!-- CSS styles: This is for me to worry about; not you. -->
<link href="css/game.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var secondsRemaining = 30;
var score = 0;
var gamerFirstName;
$(document).ready(function(){
gamerFirstName = prompt("Please enter your first name."," ");
$('div#content p').text('Hello ' + gamerFirstName + '! Are you ready? After clicking "start", you will have 30 seconds to hit as many home runs as you can. The images appear randomly so be ready!');
$('div#gamespace').html('<img src="img/baseball.png"/>');
$('div.timer').removeClass('timer');
alert(numberX());
alert(numberY());
$('button#start_button').click(playBall);
tallyScore();
$('button#start_button').css({"width": "80px","height":"40px","font-size":"18px","background-color":"#b66f42","color": "#253f38", "font-family":"baseball"});
});
function numberX(){
return Math.floor(Math.random() * 636);
};
function numberY(){
return Math.floor(Math.random() * 350);
};
function tallyScore(){
score++;
$('span#score').text( score + " pts");
};
function playBall(){
countDown();
};
function countDown(){
secondsRemaining--;
$("div.timer").text(secondsRemaining + " Seconds Left");
};
</script>
</head>
<body>
<div id="content">
<div id="contenta">
<h1><span>Home Run Derby</span></h1>
<p></p>
<div id="controls">
<span id="score">0 pts</span>
<button type="button" id="start_button">Start!</button>
</div>
<div class="timer">
30 Seconds Left
</div>
</div>
<div id="gamespace">
</div>
</div>
</body>
</html>

In your document.ready function, you have the following line which is removing the class from timer from your div, so when the countDown function executes, it cannot locate the div.timer selector.
Just remove this line:
$('div.timer').removeClass('timer');

Related

AngularJS - Remove/Add Class on element based off if element is active/hover/or contains a value

I have a magnifying glass that when you hover or click on it, it expands to a full search bar. I want the functionality to be that when the search bar is active, it will stay expanded until clicked off, or will stay expanded if the bar has a value. I have the logic in jQuery, but this is my first time using AngularJS (not Angular) and I do not know how to turn this jQuery into a directive, or if there is some built in functionality I am missing. Thank you!
jQuery("#inpt_search").on("focus", function () {
jQuery(this).parent("label").addClass("active");
});
jQuery("#inpt_search").on("blur", function () {
if (jQuery(this).val().length == 0)
jQuery(this).parent("label").removeClass("active");
});
var myApp = angular.module('myApp', []);
// set for Home Controller
myApp.controller('HomeCtrl', function($scope) {
$scope.blueClass = function() {
$scope.class_name = "blue";
$scope.multi_message ="Blue Class Added";
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.min.js"></script>
<html>
<head>
<link data-require="bootstrap-css#3.2.0" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<script data-require="angular.js#1.3.0-beta.5" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
</head>
<body ng-app="myApp">
<div class="container" ng-controller="HomeCtrl">
<div class="alert" ng-class="{blue:'bg-info', red:'bg-danger',green:'bg-success' }[class_name]">{{multi_message}}</div>
<a class="btn btn-info" ng-click="blueClass()"> Blue Class</a>
</div>
</body>
</html>

Why JQuery with SetInterval won't work on Firefox?

I am trying to learn JQuery running sample codes dealing with SetInterval or Settimeout I find on the Internet, but they won't run or work. For instance, I have the following simple code, but it won't run or even give me error message.
<!DOCTYPE html>
<html>
<head>
<title>testing</title>
<script type="text/javascript">
$(document).ready(function(){
setInterval(function() {
var number = 1 + Math.floor(Math.random() * 333);
$('#here').load(number);
},
1000);
});
</script>
</head>
<body>
<div id="here">dynamic content ?</div>
</body>
</html>
You first missed to add jquery library and second you should use .text() function rather than .load() function.
.load() function should use for ajax method.
One of the essential rules that should keep in mind that always put javascript code at the end of the page and before the end of the body tag
$(document).ready(function() {
setInterval(function() {
var number = 1 + Math.floor(Math.random() * 333);
$('#here').text(number);
}, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>testing</title>
</head>
<body>
<div id="here">dynamic content ?</div>
</body>
</html>

Sending input from HTML using callback

I have the code for the input from a user, and I have the callback, I am just confused on how to have the data sent using the callback
my code:
HTML
<!DOCTYPE html>
<html>
<head>
<base target="\_top">
</head>
<body>
<label>User info: </label>
<div align="justify">
<input type= "text" id = "email">
</div>
<br>
<button id="searchData"> Search data sheet </button>
<script>
//Above creates a box for user input [//document.getElementById](//document.getElementById)("searchData").addEventListener("click",addHeaders); document.getElementById("searchData").addEventListener("click",google.script.run.withSuccessHandler(onSuccess).testCase());
//gets the button1 element and listens for a click then runs the function addName.
function onSuccess(numUnread) {
var div = document.getElementById('output');
div.innerHTML = numUnread
} ​
google.script.run.withSuccessHandler(onSuccess).testCase()
</script>
</body>
</html>
Apps Script
function doGet() {
return HtmlService.createHtmlOutputFromFile('frontEnd');
}
function testCase(input)
{
Logger.log((input + ' hello'))
return (input + ' hello')
}
My expected would be the input + " hello", instead I got "undefined hello"
Let's say that in your html you have a button like this with a div above it:
<body>
<div id="message"></div>
<input type="button" value="Hello" onClick="sayHello();" />
<script>
//When you click the button this function gets called
function sayHello() {
google.script.run
.withSuccessHandler(function(msg){
document.getElementById("message").innerHTML=msg;//message will appear in the div
})
.sayHelloToServer();//This function is on the server
console.log('My Code');
</script>
</body>
Then in Code.gs:
function sayHelloToServer() {
return "Hello. We're very happy that you came to visit us.";//this is returned to withSuccessHandler(function(msg){}) or you can also use a standalone function in which you simply put its name in like this .withSuccessHandler(funcname)
}
This is explained in Client to Server Communication

Where does my dynamically added script go?

I'm new to web development and I'm trying to understand how the DOM works.
I have a basic page with 2 buttons and some text. One of the buttons does a call to Jquery's Get function. My server returns some html with some script as well. Which is then added to my DIV on my main page which has an ID of 'content'
See below for the code.
Main Page
<!DOCTYPE html>
<link rel="stylesheet" href="css/toastr.css">
<html>
<body>
<h1>My Main Page </h1>
<button class="alertmsg">click me</button>
<button class="addDom" >Call Add HTML</button>
<div id="content">
</div>
</body>
</html>
<script src="js/jquery.js"></script>
<script src="js/toastr.js"></script>
<script>
$(document).ready(function(){
$(".alertmsg").click(function() {
alert("Hello World!");
});
$(".addDom").click(function(){
$.get( '/adddom',
function (data) {
// put html into the section
$("div#content").html(data);
})
});
});
</script>
Code Returned
<div>
<h1>Added Via $.html</h1>
<button class="showmsg">click me for jquery</button>
</div>
<script>
$(document).ready(function(){
$(".showmsg").click(function(){
toastr.warning( "Test Warning", 'Warning');
});
});
</script>
The Updated DOM - notice that my new javascript aren't seen.
<!DOCTYPE html>
<link rel="stylesheet" href="css/toastr.css">
<html>
<body>
<h1>My Main Page </h1>
<button class="alertmsg">click me</button>
<button class="addDom" >Call Add HTML</button>
<div id="content">
<div>
<h1>Added Via $.html</h1>
<button class="showmsg">click me for jquery</button>
</div>
</div>
</body>
</html>
<script src="js/jquery.js"></script>
<script src="js/toastr.js"></script>
<script>
$(document).ready(function(){
$(".alertmsg").click(function() {
alert("Hello World!");
});
$(".addDom").click(function(){
$.get( '/adddom',
function (data) {
// put html into the section
$("div#content").html(data);
})
});
});
</script>
What I'm trying to understand is;
1) Where does my new script code exist?
<script>
$(document).ready(function(){
$(".showmsg").click(function(){
toastr.warning( "Test Warning", 'Warning');
});
});
</script>
is it in memory only and not in the DOM?
2) I can get the warning to show correctly i.e $(".showmsg").click
fires and shows what is expected. So my my script can reference the existing libraries in the DOM which are needed. How does this work?
3) What is the best way to trouble shoot this code if I cannot see it in my browser?
Many thanks!
If you really want to append the script to the dom you need to use appendChild() not .html(). link about appendChild
An example of doing this would be
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.text = 'alert("test");';
$('div')[0].appendChild(script);
Here is a fiddle showing this.

jQuery Mobile click events on dynamic list items

I'm having trouble getting click events from list items. In this page:
http://bec-systems.com/list-click.html
The first the entries in the list fire click events. However, if I dynamically add 3 more events by pushing the "Refresh Update List" button, the next 3 list entries do not generate click events.
Appreciate any suggestions as to how I can make this work, or generally improve the code.
Thanks,
Cliff
Code is also listed below:
<!DOCTYPE html>
<html>
<head>
<title>Status</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#refreshUpdateButton").on("click", function(event, ui) {
console.log("refreshUpdateButton")
versions = ["0.3", "0.4", "0.5"]
for (var i=0; i < versions.length; i += 1) {
$("#updateVersionsList").append('<li><a id="updateVersionItem-' + (i+3) + '">' + versions[i] + '</a></li>');
if ($("#updateVersionsList").hasClass('ui-listview')) {
$("#updateVersionsList").listview("refresh");
} else {
$("#updateVersionsList").trigger('create');
}
}
})
$('[id^=updateVersionItem]').on("click", function(event, ui) {
console.log("updateVersion, selected = " + $(this).attr('id'));
})
});
</script>
</head>
<body>
<!-- Software update page -->
<div data-role="page" id="software-update-page">
<div data-role="header">
<h1>Software Update</h1>
</div><!-- /header -->
<div data-role="content">
<h1>Select Software version:</h1>
<ul data-role="listview" id="updateVersionsList">
<li><a id="updateVersionItem-0">0.0</a></li>
<li><a id="updateVersionItem-1">0.1</a></li>
<li><a id="updateVersionItem-2">0.2</a></li>
</ul>
<br>
<a data-role="button" class="ui-btn-left" id="refreshUpdateButton">Refresh Update list</a>
</div><!-- /content -->
</div>
</body>
</html>
Use this form of .on() (per comments below).
$(document).on("click", '[id^=updateVersionItem]', function(event, ui) {
console.log("updateVersion, selected = " + $(this).attr('id'));
})
Example: http://jsfiddle.net/saluce/YaAEJ/
Otherwise, whenever you dynamically add the new elements, you need to attach the click event to those items.
Assuming the following code:
function doThisOnClick(event, ui) {
console.log("updateVersion, selected = " + $(this).attr('id'));
}
$('[id^=updateVersionItem]').on("click", doThisOnClick);
You can either unbind the handler and reattach to all matching items:
$('[id^=updateVersionItem]').off("click", doThisOnClick);
$('[id^=updateVersionItem]').on("click", doThisOnClick);
Or just dynamically add it to the new items once you add it:
$("#updateVersionsList").append('<li><a id="updateVersionItem-' + (i+3) + '">' + versions[i] + '</a></li>').on("click", doThisOnClick);
create a new function and call it for default and dynamic elements
<a onclick="myfunction()">