JavaScript not working with android WebView, Uncaught ReferenceError - javascript

I am trying to load a web app on android using WebView and the JavaScript in my html files is not executing properly.
I create the WebView and load the home page like this:
web = new WebView(this);
web.getSettings().setJavaScriptEnabled(true);
web.getSettings().setDomStorageEnabled(true);
JavaScriptInterface jsInterface = new JavaScriptInterface(web, this);
web.setWebChromeClient(new WebChromeClient());
web.addJavascriptInterface(jsInterface, "JSInterface");
web.loadUrl("file:///android_asset/web/home.html");
Once the home page is loaded I click a link to another local page, register.html, where I have a JavaScript function in the head
<script type="text/javascript">
function doRegister() {
var user = document.getElementById("username").value;
var email = document.getElementById("email").value;
var pass = document.getElementById("password").value;
var confPass = document.getElementById("confirmPassword").value;
var message = "";
if (user.length < 6 || user.length > 16) {
message = message + "Username must be between 6 and 16 characters.<br>";
}
if (pass.length < 8 || pass.length > 16) {
message = message + "Password must be between 8 and 16 characters.<br>";
}
if (pass !== confPass) {
message = message + "Password and confirm password do not match.<br>";
}
if (email.indexOf("#") === -1) {
message = message + "Email address is invalid.<br>";
}
if (message === "") {
message = JSInterface.register(user, email, pass);
if (message === "") {
window.location.href = "home.html";
}
}
document.getElementById("message").style.color="red";
document.getElementById("message").innerHTML=message;
}
</script>
This function is called by a buttons onclick like so
<input id="register" type="button" value="Submit" data-role="button" data-inline="true" data-theme="b" onclick="doRegister()" />
It appears that when the button is clicked it is trying to call doRegister() on home.html. When I click the button i get Uncaught ReferenceError: doRegister is not defined at file:///android_asset/web/home.html:1
To confirm this, I added a JavaScript function to home.html that just displays an alert and this did indeed execute when I clicked the button in register.html
Any help on this problem would be greatly appreciated. Thanks.
Update: Forgot to mention, the JavaScript executes fine in the eclipse web browser as well as firefox. Here is my home.html
<!doctype html>
<html>
<head>
<title>Home</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css">
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="pagination/jquery.simplePagination.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript>
function doSubmit() {
alert("test");
}
</script>
</head>
<body>
<div data-role="page" id="home">
<div data-role="header" data-theme="b">
<h1>Home</h1>
</div>
<div data-role="content">
<ul data-role=listview>
<li> <a href = professors.html> Browse Professors </a> </li>
<li> <a> Search Professors </a> </li>
<li> <a> Browse Course </a> </li>
<li> <a> Search Course </a> </li>
<li> <a href = login.html> Login </a> </li>
<li> <a href = register.html> Register </a> </li>
</ul>
</div>
<div data-role="footer">
<h4>footer</h4>
</div>
</div>
</body>
</html>

Basically webview is not able to find the function doRegister() , sine that is in a different html page register.html, which is not loaded. Try this
1. Move the js portion in register.html to some .js file say func.js
2. Then refer to func.js from your home.html as
<script type="text/javascript" src="func.js"></script>
3. once page is loaded, clicking on the button should call doRegister()

Related

clicking next page causes my page to slow down exponentially

this is my first time asking a question on Stack Overflow, any help would be greatly appreciated.
I have a website that displays images from the pixabay api. When i click the button, next, the next page of images is shown. The problem is that with each click, the page slows down at an exponential rate. I know this because i added a success console.log after every completion.
This is the image before:
Image Link Here.
and after
Image Link Here
I think the problem has something to do with the .getJSON call and the for loop inside that call, but I havn't been able to figure it out.
This is the Javascript and HTML
/*
Pixabay api key:
*/
$(document).ready(function () {
var searchValue = "rice"
var defaultPage = 1;
returnPhotos(searchValue, defaultPage);
$("#searchForm").on("submit", function (event) {
//obtain value from user input
searchValue = $("#searchText").val();
returnPhotos(searchValue, defaultPage);
//stops form from submitting to a file
event.preventDefault();
});
});
/*
1. Return Photos from pixabey API
*/
function returnPhotos(searchValue, pageNum) {
let key = "8712269-5b0ee0617ceeb0fd2f84487c3";
let startURL = "https://pixabay.com/api/?key=" + key;
let page = "&page=" + pageNum;
let imagesPerPage = "&per_page=" + 22
let addWH = "&min_width&min_height";
let safeSearch = "&safesearch=true";
let endingURL = "&q=" + searchValue + page + addWH + safeSearch + imagesPerPage;
// activate api and get data
$.getJSON(startURL + endingURL, function (data) {
let image = data.hits;
var imageLength = image.length;
arrayLength = image.length;
if (data) {
let output = ""
for (let x = 0; x < arrayLength; x++) {
//imageObject contains information on each image passed through the array
let imageObject = {
// id: image[x].id,
// pageURL: image[x].pageURL,
// tags: image[x].tags,
// previewURL: image[x].previewURL,
// previewWidth: image[x].previewWidth,
// previewHeight: image[x].previewHeight,
// webformatURL: image[x].webformatURL,
// webformatWidth: image[x].webformatWidth,
// webformatHeight: image[x].webformatHeight,
largeImageURL: image[x].largeImageURL,
// fullHDURL: image[x].fullHDURL,
// views: image[x].views,
// user_id: image[x].user_id,
// user: image[x].user,
// userImageURL: image[x].userImageURL
}
// output this template to the website
output += `
<div class="brick">
<img src="${imageObject.largeImageURL}">
</div>
`
}
$(".masonry").imagesLoaded(function () {
localStorage.clear();
$(".masonry").html(output);
});
console.log("success");
} else {
console.log("Didn't work");
}
getPage(searchValue, pageNum, arrayLength);
// console.log(arrayLength);
});
}
/*
2. INCREASE/Decrease PAGE
*/
function getPage(searchValue, defaultPage, max) {
if (defaultPage <= max + 1) {
$("#pagination2").click(function () {
if (defaultPage <= max) {
defaultPage++;
returnPhotos(searchValue, defaultPage);
console.log(1);
}
$(".pageNumber").html("Page " + defaultPage);
console.log("This is the default page:", defaultPage);
});
}
$("#pagination1").click(function () {
if (defaultPage != 1) {
defaultPage--;
returnPhotos(searchValue, defaultPage);
console.log(1);
}
$(".pageNumber").html("Page " + defaultPage);
console.log("This is the default page:", defaultPage);
});
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv='cache-control' content='no-cache'>
<title>Photo Gallery</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/css?family=Lato:300,400" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="vendors/css/ionicons.min.css">
<link rel="stylesheet" type="text/css" href="vendors/css/animate.min.css">
<link rel="stylesheet" href="resources/css/style.css">
<link href="data:image/x-icon;base64,AAABAAEAICAAAAEAIACoEAAAFgAAACgAAAAgAAAAQAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////+4z/L/pMLv//j6/f///////v7//6vG8P+lwu//5u76/3ek5/+70fP///////7+/v+wyvH/daLn/9Hg9////////////////////////////////////////////////////////////////////////////////////////////1SM4f8kbNn/8PX8///////H2vX/CFnU/4yy6v/W4/j/ClvU/4St6f//////y9z2/xVi1v9QiuD/9Pf9////////////////////////////////////////////////////////////////////////////////////////////VIzh/yRs2f/w9fz/9Pf9/z9+3f9Egd7/8/f9/9bj+P8KW9T/hK3p/+7z+/8ob9n/LXLa//D0/P////////////////////////////////////////////////////////////////////////////////////////////////9UjOH/JGzZ/87e9v+Bqun/CVrU/8zc9v//////1uP4/wpb1P9+qej/ZZfk/xdj1v/J2/X//////////////////////////////////////////////////////////////////////////////////////////////////////1SM4f8kbNn/jrPr/zB02/8RX9X/e6bo//X4/f/W4/j/ClvU/2+e5v8faNj/oL/u////////////////////////////////////////////////////////////////////////////////////////////////////////////VIzh/yRs2f/w9fz/+vz+/6zH8P8EVtP/p8Tv/9bj+P8KW9T/cqDm/yRs2f9ek+P/+fv+//////////////////////////////////////////////////////////////////////////////////////////////////////9UjOH/JGzZ//D1/P///////v7//xJf1f9vnuX/1uP4/wpb1P+ErOn/nb3t/wdY1P+cvO3//v7//////////////////////////////////////////////////////////////////////////////////////////////////1SM4f8kbNn/8PX8//7+///J2/X/BFbT/5G17P/W4/j/ClvU/4St6f/5+/7/RoLe/xZi1v/e6fn/////////////////////////////////////////////////////////////////////////////////////////////////VIzh/yRs2f+au+3/RYLe/xdj1v9bkeL/7/T8/9bk+P8MXNX/ha3q///////W4/f/GmXX/0iE3//1+P3///////////////////////////////////////////////////////////////////////////////////////////+70fP/p8Tv/8fZ9f+jwe//xtn1/8nMz/+Ojo7/vcDG/77S8v/f6fn///////7+/v/P3/b/wNT0//T4/f/////////////////////////////////////////////////////////////////////////////////////////////////////////////////39/f/aWlp/9jY2P9ycnL/29vb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////v7+/9LS0v/CwsL/9/f3//r6+v9oaGj/vr6+/2xsbP/f39//7Ozs/729vf/j4+P//v7+//////////////////////////////////////////////////////////////////////////////////////////////////////+7u7v/f39//6CgoP+JiYn//v7+/+Hh4f+pqan/29vb//n5+f9mZmb/qqqq/2xsbP/h4eH//////////////////////////////////////////////////////////////////////////////////////////////////////6urq/+ampr/0NDQ/3d3d//9/f3/rMfw/9nl+P+zzPH/9vb2/2RkZP/c3Nz/eXl5/9jY2P//////////////////////////////////////////////////////////////////////////////////////////////////////9/f3/5mZmf+Li4v/5OTk/+Hr+f+Msuv/ydv1/42y6//u9Pz/ysrK/4aGhv+0tLT//Pz8/////////////////////////////////////////////////////////////////////////////////////////////////////////////Pz8//j4+P/4+v3/XJHi/+Xt+v//////irHq/7nQ8//+/v7/9fX1//7+/v///////////////////////////////////////////////////////////////////////////////////////////////////////////9nZ2f9ra2v/b29v/7e3t//k7fr/bp3l/6C/7v+xyvH//Pz8/42Njf91dXX/eHh4//Dw8P//////////////////////////////////////////////////////////////////////////////////////////////////////o6Oj/7a2tv/t7e3/bW1t//b4/P/U4vf/4Or5/+nw+//z8/P/ZmZm//b29v+FhYX/09PT///////////////////////////////////////////////////////////////////////////////////////////////////////g4OD/eXl5/3l5ef+/v7///Pz8/6Kiov+FhYX/vr6+//39/f+Xl5f/gYGB/4WFhf/z8/P////////////////////////////////////////////////////////////////////////////////////////////////////////////4+Pj/9PT0///////Ozs7/hoaG/97e3v9tbW3/6+vr//39/f/w8PD//f39/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////+fn5/9vb2//mpqa/3d3d//09PT//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////+Dg4P/IyMj/7e3t////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
rel="icon" type="image/x-icon" />
</head>
<body>
<div class="container">
<nav class="nav">
<h1>
<a class="brand-logo" href="index.html">Photo Gallery</a>
</h1>
</nav>
<!-- IMAGE search box-->
<div class="header">
<div>
<h3 class="text-center">Search For Any Image</h3>
<form id="searchForm" autocomplete="off">
<input type="text" class="form-control" id="searchText" placeholder="Search Image Here">
</form>
<h4 class="from-pixabay">Images from Pixabay</h4>
</div>
<div class="paginations">
Previous
<p class="pageNumber">Page 1</p>
Next
</div>
</div>
<!-- IMAGES GO HERE -->
<div class="masonry">
</div>
</div>
<!-- Pre-footer -->
<!--SECTION Contact-Footer -->
<footer class="footer-section" id="contact">
<div class="rows-container">
<div class="footer-con">
<div class="homepage-link">
<a href="http://rkdevelopment.org" target="_blank">
<h3>Rkdevelopment.org</h3>
</a>
</div>
<ul class="social-list center">
<li>
<a href="https://github.com/RexfordK" target="_blank">
<i class="ion-social-github"></i>
</a>
</li>
<li>
<a href="https://www.linkedin.com/in/rexford-koduah" target="_blank">
<i class="ion-social-linkedin"></i>
</a>
</li>
<li>
<a href="https://www.freecodecamp.org/rexfordk" target="_blank">
<i class="ion-fireball"></i>
</a>
</li>
</ul>
<p>Copyright © 2018 by Rexford Koduah. All rights reserved.</p>
</div>
</div>
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://unpkg.com/imagesloaded#4/imagesloaded.pkgd.min.js"></script>
<script src="resources/js/main.js"></script>
</body>
</html>
Every time you call getPage, you are adding another $("#pagination2").click handler. Which means the first time you click it, you do one ajax request. The second time you do two, the third time you do three, etc. You need to either only setup the click handler once, and make sure your logic reflects that, or clear the old one each time with $("#pagination2").off('click').click(

Unable to implement Singalr notifications to existing MVC project

I tried to implement Signalr notification to my existing MVC project and my code in the View as follows
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - My ASP.NET Application</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<span class="noti glyphicon glyphicon-bell"><span class="count"> </span></span>
<div class="noti-content">
<div class="noti-top-arrow"></div>
<ul id="notiContent"></ul>
</div>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { #class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>#Html.ActionLink("Home", "Index", "Home")</li>
<li>#Html.ActionLink("About", "About", "Home")</li>
<li>#Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
#Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© #DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
#* Add Jquery Library *#
<script src="~/Scripts/jquery-2.2.3.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="/signalr/hubs"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
#* Add css *#
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<style type="text/css">
/*Added css for design notification area, you can design by your self*/
/* COPY css content from youtube video description*/
</style>
#* Add jquery code for Get Notification & setup signalr *#
<script type="text/javascript">
$(function () {
// Click on notification icon for show notification
$('span.noti').click(function (e) {
e.stopPropagation();
$('.noti-content').show();
var count = 0;
count = parseInt($('span.count').html()) || 0;
//only load notification if not already loaded
if (count > 0) {
updateNotification();
}
$('span.count', this).html(' ');
})
// hide notifications
$('html').click(function () {
$('.noti-content').hide();
})
// update notification
function updateNotification() {
$('#notiContent').empty();
$('#notiContent').append($('<li>Loading...</li>'));
$.ajax({
type: 'GET',
url: '/home/GetNotificationContacts',
success: function (response) {
$('#notiContent').empty();
if (response.length == 0) {
$('#notiContent').append($('<li>No data available</li>'));
}
$.each(response, function (index, value) {
$('#notiContent').append($('<li>New contact : ' + value.ContactName + ' (' + value.ContactNo + ') added</li>'));
});
},
error: function (error) {
console.log(error);
}
})
}
// update notification count
function updateNotificationCount() {
var count = 0;
count = parseInt($('span.count').html()) || 0;
count++;
$('span.count').html(count);
}
// signalr js code for start hub and send receive notification
var notificationHub = $.connection.notificationHub;
$.connection.hub.start().done(function () {
console.log('Notification hub started');
});
//signalr method for push server message to client
notificationHub.client.notify = function (message) {
if (message && message.toLowerCase() == "added") {
updateNotificationCount();
}
}
})
</script>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
</body>
</html>
In the Line
// signalr js code for start hub and send receive notification
var notificationHub = $.connection.notificationHub;
$.connection.hub.start().done(function () {
console.log('Notification hub started');
});
$.connection does not have a definition
and When running the application
Uncaught TypeError: Cannot read property 'notificationHub' of undefined
at HTMLDocument.<anonymous> (Login:219)
at i (jquery-2.2.3.min.js:2)
at Object.fireWith [as resolveWith] (jquery-2.2.3.min.js:2)
at Function.ready (jquery-2.2.3.min.js:2)
at HTMLDocument.J (jquery-2.2.3.min.js:2)
It shows the error line as
var notificationHub = $.connection.notificationHub;
But when I tried to implement in a new project it worked after removing some additional scripts references, but in this project it did not worked
Here is the example I followed
http://www.dotnetawesome.com/2016/05/push-notification-system-with-signalr.html
This works fine for empty MVC project but when trying to implement the same to existing one gives this issue.
// signalr js code for start hub and send receive notification var notificationHub = $.connection.notificationHub;
$.connection does not have a definition which should come from jquery.signalR-2.2.0.js
Any idea to solve this issue
i'm also developing a project with signalr and i guess also that this is a referencing problem.
Look at your code again, the line:
<script src="~/Scripts/jquery-2.2.3.min.js"></script>
and the line:
#Scripts.Render("~/bundles/jquery")
Here you are referencing your jQuery libraries 2 times. I would refactor the referencing and keep it only in one place and before the signalr code. Because signalr depends on jquery library. I suggest you to go with this hierarchy:
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/bundles/jqueryTables")
<script src="~/signalr/hubs"></script>
#RenderSection("scripts", required: false)
Hope it helps. Let me know it you have any question!!

Why the method innerHTML is making a change inside the html file, but it is not been displayed in the browser?

Why the method innerHTML is making a change inside the html file, but it is not been displayed in the browser? The idea is that when a user logged in, his name will be displayed in the header. I think that the problem is that header is loaded from the start, but I am making sure that the header is loaded before making any change. At the same time, the logout button is not working and I think that is for the very same issue.
FILE: index.html
<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script src="js/jquery.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase.js"></script>
<script src="js/init.js"></script>
<script src="js/index.js"></script>
<script>
$(function(){
$("#header").load("header.html");
$("#footer").load("footer.html");
});
</script>
</head>
<body>
<div id="header"></div>
<div id="newsfeed"></div>
<div id="footer"></div>
</body>
</html>
FILE: header.html
<header>
<div class="generalHeader">
<div class="header01">
WOC
<div class="loggedAs">
Welcome,
<a id="username"></a>!<br>
<button id="logout_button">Log out.</button>
</div>
</div>
<div class="header02">
<ul class="menu" >
<li><a class="active" href="">ALL</a></li>
<li><a class="static">&nbsp&nbsp&nbsp&nbsp|&nbsp&nbsp&nbsp&nbsp</a></li>
<li><a class="desactive" href="">RECOMMENDED</a></li>
<li><a class="static">&nbsp&nbsp&nbsp&nbsp|&nbsp&nbsp&nbsp&nbsp</a></li>
<li><a class="desactive" href="">SAVED</a></li>
<li><a class="static"> &nbsp&nbsp&nbsp|&nbsp&nbsp&nbsp&nbsp</a></li>
<li><a class="desactive" href="">POPULAR</a></li>
<li><a class="static">&nbsp&nbsp&nbsp&nbsp|&nbsp&nbsp&nbsp</a></li>
<li><a class="desactive" href="">CATEGORIES</a></li>
</ul>
</div>
</div>
</header>
FILE: index.js
$(document).ready(function() {
$("#header").load("header.html", function(){
console.log("Header loaded.");
// Set up UI elements
var newsfeed = document.querySelector("#newsfeed"),
username = document.querySelector("#username"),
logout_button = document.querySelector("#logout_button");
//Set user attributes
var user_info, user_display_name;
//Initialize Firebase
var auth = firebase.auth(),
storage = firebase.storage(),
database = firebase.database();
console.log("Firebase inizialized.");
//Logout
logout_button.addEventListener('click', function(e){
auth.signOut();
console.log("You have been logged out");
window.location = "index.html";
});
//Check user auth
auth.onAuthStateChanged(function(user) {
//Get user full data
user_info = user;
if(user){
console.log("User detected.");
user_display_name = user_info.displayName;
console.log("User display name read. User display name =", user_display_name);
//Assign username to header
username.innerHTML = user_display_name;
console.log("username, ",username);
}else{
window.location = "login.html";
}
});
//Get newsfeed
//Listen from the latest 10 stories onwads, and display them
database.ref("events").on('child_added', function(snapshot){
displayEvent(snapshot.val());
});
//Listen to whenever a story changes
database.ref("events").on('child_changed', function(snapshot){
displayEvent(snapshot.val());
});
function displayEvent(value){
console.log(value.imageUrl);
storage.ref(value.imageUrl).getDownloadURL()
.then(function(url) {
$("#newsfeed").append("\<div class=\"event\"\>\<div class=\"event_title\"\>"+value.title+"\<\/div\>\<img class=\"event_image\" src=\""+url+"\"\/\>\<div class =event_header\>\<div class=\"event_info_header\" id=\"event_hour\"\>"+value.hour+"\<\/div\>\<div class=\"event_info_header\" id=\"event_date\"\>"+" | "+value.date+" | "+"\<\/div\>\<div class=\"event_info_header\" id=\"event_place\"\>"+value.place+"\<\/div\>\<\/div\>\<div class=\"event_brief_description\"\>"+value.brief_description+"\<\/div\>\<\/div\>");
console.log("Event displayed");
});
}
});
});

JQuery dynamic html page

When the button is pressed i would like for another div tag to appear on the screen for the user. I have tried and looked through many web pages to see what is going wrong. There is no error on the console for the webpage. Here is the HTML code and JavaScript code.
/*jslint browser: true*/
/*global $, jQuery, alert*/
$("buttonId").click(function () {
var structure = $("<div>Hello world</div>");
$("#newDiv").append(structure);
document.getElementById("div01").style.backgroundColor = "red";
});
<html>
<head>
<link rel="stylesheet" href="site.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<nav>
<p class="logo"> Logo! </p>
<ul id="ul01">
<li>NewsFeed</li>
<li>Discover</li>
<li>Following</li>
</ul>
<div class="logIn">
Login
Sign Up
</div>
</nav>
<a id="buttonId" href="#"> Click fo anouther div!!</a>
<div id=newDiv>
<div id=div01> Hello </div>
</div>
<script src="operations.js"></script>
</body>
</html>
$("buttonId") is a selector that won't match any element (as it searches for an element with a tag buttonId).
You should change it to $("#buttonId") for it to work.
There were some mistakes in your code.
$("buttonId").click(function () {
var structure = $("<div>Hello world</div>");
$("#newDiv").append(structure);
document.getElementById("div01").style.backgroundColor = "red";
});
In the above code. # character is missing before buttonId. So it will not match anything. This is the corrected version
$("#buttonId").click(function () {
var structure = $("<div>Hello world</div>");
$("#newDiv").append(structure);
document.getElementById("div01").style.backgroundColor = "red";
});
Also in your HTML, you have forgotten to place double quotes outside ids of newDiv and div01. Here is the corrected version
<html>
<head>
<link rel="stylesheet" href="site.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<nav>
<p class="logo"> Logo! </p>
<ul id="ul01">
<li>NewsFeed</li>
<li>Discover</li>
<li>Following</li>
</ul>
<div class="logIn">
Login
Sign Up
</div>
</nav>
<a id="buttonId" href="#"> Click fo anouther div!!</a>
<div id="newDiv">
<div id="div01"> Hello </div>
</div>
<script src="operations.js"></script>
</body>
</html>
It appears as though you're missing the '#' sign in front of your $('buttonId').
So it should be:
$("#buttonId").click(function () {
var structure = $("<div>Hello world</div>");
$("#newDiv").append(structure);
document.getElementById("div01").style.backgroundColor = "red";
});
Cheers,
David

Javascript function not running with no errors

here is my function which is put into its own file(Javascript/submitDate.js):
document.onload = function(){
function submitDate(){
var time = new Date();
var nowDate =time.toISOString().slice(0,-14);
document.getElementById("dateShow").value=nowDate;
}
submitDate();
}();
This ran fine before I joined the page with my index.(When I put all my javascript and page layout into one file)
Here is the page(projectMain.html) of the code:
<html>
<div id="container">
<header>
<h3>Entries close on the 10th of March</h3>
</header>
<section>
<aside onload="submitDate();">
Last submitted:
</br>
<input type="date" id="dateShow" readonly>
</aside>
</section>
No errors pop up and it just shows the date layout box as: mm/dd/yyyy
EDIT:
The folder has a capital J.
Edit 2.0:
Link to what is shown. Underneath the "last submitted" is the date function that is not working. : http://prntscr.com/60ie8k
Edit 3.0:
Here is my Index:
<html>
<head>
<title>Sample Template</title>
<link rel="stylesheet" language="text/css" href="CSS/stylesheet.css"/>
<script language="javascript" src="Javascript/AJAX.js"></script>
</head>
<body onload="javascript:changePage('home');">
<h1>Little Big Planet</h1>
<div class="menu">
<a onclick="javascript:changePage('home');">Home</a>
<a onclick="javascript:changePage('powerups');">Power Ups</a>
<a onclick="javascript:changePage('bots');">Sackbots</a>
<a onclick="javascript:changePage('costumes');">Costumes</a>
<a onclick="javascript:changePage('projectMain');">Form</a>
</div>
<br />
<div id="content">
</div>
<script type="text/javascript" src="Javascript/submitDate.js"></script>
</body>
</html>
The aside element doesn't have an onload attribute (or load event). Only elements that load external content (e.g. <img>) and the document itself (where the attribute lives on the <body> element) do.
Use a <script> element instead.
<aside>
Last submitted:
</br>
<input type="date" id="dateShow" readonly>
</aside>
<script>
submitDate();
</script>
Additionally, you say that the file lives at "javascript/submitDate.js" but you are loading src="Javascript/submitDate.js". The function won't be available to call if you are using a case-sensitive file system (as the URL will 404).
You have a capitol 'j' in JavaScript in your HTML.
<script type="text/javascript" src="Javascript/submitDate.js"></script>
Try loading the js when the document is loaded
JS file:
document.onload = function(){
function submitDate(){
var time = new Date();
var nowDate =time.toISOString().slice(0,-14);
document.getElementById("dateShow").value=nowDate;
}
submitDate();
}();
The aside in your html
<aside>
Last submitted:
</br>
<input type="date" id="dateShow" readonly>
</aside>
Link to js file in the bottom of your body
<script type="text/javascript" src="pathtojsfile"></script>
Here is a working Fiddle

Categories