button onclick not working on first click - javascript

my button.onclick doesn't work on the first click, but it works on the second.
I used an alert to check and even the alert doesnt work on the first click, but works on the second click.
here's the link to the app in case you need it -
http://silentarrowz.imad.hasura-app.io/news
could you tell me what's wrong??
here's the code
window.onclick = function () {
var displayNews = document.getElementById('currentNews');
var newsButton = document.getElementById('getnews');
newsButton.onclick = function () {
alert('the button is clicked');
var newsxr = new XMLHttpRequest();
newsxr.onreadystatechange = function () {
if (newsxr.readyState === XMLHttpRequest.DONE && newsxr.status === 200) {
var currentNews = JSON.parse(newsxr.responseText);
var currentArticles = currentNews['articles'];
var numberArticles = currentNews['articles'].length;
var newsDisplay = '';
var author;
var title;
var description;
var urlToImage;
for (var i = 0; i < numberArticles; i++) {
author = currentArticles[i]['author'];
title = currentArticles[i]['title'];
description = currentArticles[i]['description'];
urlToImage = currentArticles[i]['urlToImage'];
newsDisplay = newsDisplay + "<p>" + "<span class='title'>" + title + "</span>" + "<br>" + description + "<br>" + "<img src='" + urlToImage +
"'</img>" + "</p>";
}
alert('displaying the news now');
console.log('current news is : ', currentNews);
displayNews.innerHTML = newsDisplay;
}
}; //on state change
newsxr.open('GET', 'https://newsapi.org/v1/articles?source=national-geographic&sortBy=top&apiKey=1af110441a8e4f72925f78344e58c2a4', true);
newsxr.send(null);
}; //button onclick function ends
}; // window onclick function ends

The truth about your code is the following..
You are assigning an onclick event to the window. when you click the window it then gets the buttons id which then assigns an onclick event to your button.
Your button only works when you click anywhere in the window (your browser User interface). You can try it and see
SOLUTION
remove the on window.onclick event stuff.
this should be the only code you should be seeing in your editor to make things work.
var displayNews = document.getElementById('currentNews');
var newsButton = document.getElementById('getnews');
newsButton.onclick = function(){
alert('the button is clicked');
var newsxr = new XMLHttpRequest();
newsxr.onreadystatechange = function(){
if(newsxr.readyState ===XMLHttpRequest.DONE && newsxr.status ===200){
var currentNews = JSON.parse(newsxr.responseText);
var currentArticles = currentNews['articles'];
var numberArticles = currentNews['articles'].length;
var newsDisplay ='';
var author;
var title;
var description;
var urlToImage;
for(var i=0;i<numberArticles;i++){
author = currentArticles[i]['author'];
title = currentArticles[i]['title'];
description = currentArticles[i]['description'];
urlToImage = currentArticles[i]['urlToImage'];
newsDisplay = newsDisplay + "<p>"+"<span class='title'>"+ title+"</span>"+ "<br>"+description+"<br>"+"<img src='"+urlToImage+"'</img>"+"</p>";
}
alert('displaying the news now');
console.log('current news is : ',currentNews);
displayNews.innerHTML = newsDisplay;
}
};//on state change
newsxr.open('GET','https://newsapi.org/v1/articles?source=national-geographic&sortBy=top&apiKey=1af110441a8e4f72925f78344e58c2a4',true);
newsxr.send(null);
};
//button onclick function ends
I hope this was explanatory

Because the first click is window.onclick = function() part which tells the window to define another click event only, and then the real click event will work when you click the second time.
Deleting the window click event already suffices.
P.S. I don't see why having window click event is meaningful in your code.

Related

dynamic list in javascript how to call function from specific <li>

I get the message list from the API and create a dynamic array using javascript. I would like a new page with message details to be started when a specific row is pressed.
How do I implement a call to showMessage () on a specific table row?
var list = document.getElementById("listOfMessage");
init();
function init() {
for (var i = 0; i < messageList.length; i++) {
var message = messageList[i];
var li = document.createElement("li");
var a = document.createElement("a");
var text = document.createTextNode("Nadawca: " + message.fullName);
a.appendChild(text);
a.setAttribute('onclick', showMessage(message));
list.appendChild(li);
//list.innerHTML += "<li><a href="showMessage(message)"><h2>Nadawca: " + message.fullName + "
//</h2></a></li>";
}
//list = document.getElementById("listOfTask");
}
function showMessage(message) {
window.sessionStorage.setItem("message", JSON.stringify(message));
window.location.href = 'message.html';
}
In the code above, the showMessage () function is immediately called when the array is initialized. How to make it run only after clicking on a row?
I could add an id attribute to the (a) or (li) element in the init () function, but how to find it later and use it in this code:
var a = document.getElementById('1');
a.addEventListener('click', function() {
window.sessionStorage.setItem("message", JSON.stringify(messageList[0]));
window.location.href = 'message.html';
});
I found a way to solve this problem.
Using this code fragment, we can call a function for a specific element in a dynamically created list.
function init() {
for (var i = 0; i < messageList.length; i++) {
var message = messageList[i];
list.innerHTML += "<li id="+i+"><a onClick="+
"><h2>Nadawca: " + message.fullName + "</h2></a></li>";
}
//$(document).on("click", "ui-content", function(){ alert("hi"); });
$(document).ready(function() {
$(document).on('click', 'ul>li', function() {
var idName = $(this).attr('id');
showMessage(messageList[idName]);
});
});
}

Why can an event not be attached in the script but in the console?

I want to dynamically create, populate and clear a list with html and javascript. The creation and population of the list work just fine, but when I want to add the delete-button to the list item I can't attach the onclick event to the newly created element. Here is my complete function, it is called every time some changes happen to the printlist array:
var printlist = [];
var awesome = document.createElement("i");
awesome.className = "fa fa-minus";
function addToList(stationid, stationname)
{
var object = {id: stationid, name: stationname};
printlist.push(object);
drawList();
}
function removeFromList(id)
{
printlist.splice(id, 1);
drawList();
}
function drawList()
{
if (printlist.length > 0)
{
document.getElementById("printListDialog").style.visibility = 'visible';
var dlg = document.getElementById("DlgContent");
dlg.innerHTML = "";
for (var i = 0; i < printlist.length; i++)
{
var item = document.createElement("li");
item.className = "list-group-item";
var link = document.createElement("a");
link.href = "#";
link.dataset.listnumber = i;
link.style.color = "red";
link.style.float = "right";
link.appendChild(awesome);
link.onclick = function(){onRemove();};
item.innerHTML = printlist[i].name + " " + link.outerHTML;
dlg.appendChild(item);
}
}
else
{
document.getElementById("printListDialog").style.visibility = 'hidden';
}
}
function onRemove(e)
{
if (!e)
e = window.event;
var sender = e.srcElement || e.target;
removeFromList(sender.dataset.listnumber);
}
I tried:
link.onclick = function(){onRemove();};
as well as
link.addEventListener("click", onRemove);
Neither of those lines successfully adds the event from the script. However when I call any of the 2 lines above from the console it works and the event is attached.
Why does it work from the console but not from the script?
link.onclick = function(){onRemove();};
doesn't work because you're not passing through the event argument. link.onclick = onRemove should work just as your addEventListener call.
However, both of them don't work because of the line
item.innerHTML = printlist[i].name + " " + link.outerHTML;
which destroys the link element with all its dynamic data like .dataset or .onclick, and forms a raw html string that doesn't contain them. They're lost.
Do not use HTML strings!
Replace the line with
item.appendChild(document.createTextNode(printlist[i].name + " "));
item.appendChild(link); // keeps the element with the installed listener

How to add a (1) text notficiation on document title

Hi I've read here about browser tab notifications
This is the code suggested to achieve an (1) on the browser tab every second.
var count = 0;
var title = document.title;
function changeTitle() {
count++;
var newTitle = '(' + count + ') ' + title;
document.title = newTitle;
}
function newUpdate() {
update = setInterval(changeTitle, 1000);
}
var docBody = document.getElementById('site-body');
docBody.onload = newUpdate;
I've tried it and do not seem to work. Can't see why.. Input?
DEMO
http://tutsplus.github.io/tab-notification/index.html
If it's like in the example, script loaded within the body tags, try this one:
var count = 0;
var title = document.title;
var update;
function changeTitle() {
count++;
var newTitle = '(' + count + ') ' + title;
document.title = newTitle;
}
(function() {
update = setInterval(changeTitle, 1000);
})();
Also in your code variable update is undeclared. And you're not using it, so try delete "update".
don't use element.onload because it's still doesn't have (load) that Id when you are run code,check only
if(docBody) newUpdate();

JQuery button.click() handler fires without click

Right now I'm doing some clean up code for my auction game, but my function is fired immediately after endAuction() is called rather than when the button is clicked. I can't seem to figure out why, and I'm not terribly familiar with JavaScript or jQuery, can anyone point out my issue?
endAuction:function()
{
var i = 0;
var btnID = "as" + (i).toString(),
liID = "asli" + (i).toString();
var cleanBtn = $('li#' + liID + ' button#' + btnID);
cleanBtn.text("Sold!");
var btn = $('#' + btnID);
btn.off().click(this.cleanUpAuction());
},
cleanUpAuction:function()
{
console.log("Removing button");
userStats.money += currentBid;
currentBid = 0;
var i = 0;
var liID = "asli" + (i).toString();
var carElement = $('li#' + liID);
carElement.remove();
},
You are calling the function, not assigning a reference to it.
Change
.click(this.cleanUpAuction())
to
.click(this.cleanUpAuction)
or
.click($.proxy(this.cleanUpAuction, this))

Uncaught TypeError: Cannot set property 'onfocus' of null

I am trying to learn JavaScript and I'm building this basic tutorial. In trying to demonstrate onfocus and onblur, I get this error message in my JavaScript console: Uncaught TypeError: cannot set property 'onfocus' of null.
Here is my code. I am new to learning JavaScript and could really use some help.
//alert("Hello, world!");
// this is a JavaScript alert button
//
var year = 2014;
var userEmail = "";
var todaysDate = "";
/*var donation = 20;
if (donation < 20) {
alert("For a $20 you get a cookie. Change your donation?");
}
else {
alert("Thank you!");
} */
var mainfile = document.getElementById("mainTitle");
console.log("This is an element of type: ", mainTitle.nodeType);
console.log("The inner HTML is ", mainTitle.innerHTML);
console.log("Child nodes: ", mainTitle.childNodes.length);
var myLinks = document.getElementsByTagName("a");
console.log("Links: ", myLinks.length);
var myListElements = document.getElementsByTagName("li");
console.log("List elements: ", myListElements.length);
var myFirstList = document.getElementById("2 paragraphs");
/* you can also use: var limitedList = myFirstList.getElementsByTagName("li");
to dig deeper into the DOM */
var myElement = document.createElement("li");
var myNewElement = document.createElement("li");
//myNewElement.appendChild(myNewElement);
var myText = document.createTextNode("New list item");
myNewElement.appendChild(myText);
// creating elements
var newListItem = document.createElement("li");
var newPara = document.createElement("p");
// To add content, either use inner HTML
// or create child nodes manually like so:
// newPara.innerHTML = "blah blah blah...";
var paraText = document.createTextNode("And now for a beginner level intro to JavaScript! YAY!");
newPara.appendChild(paraText);
//And we still need to attach them to the document
document.getElementById("basic").appendChild(newPara);
var myNewElement = document.createElement("li");
var secondItem = myElement.getElementsByTagName("li")[1];
myElement.insertBefore(myNewElement, secondItem);
// An example of using an anonymous function: onclick.
//When you click anywhere on the page, an alert appears.
//document.onclick = function() {
// alert("You clicked somewhere in the document");
//}
// And example of restricting the click alert to
// an element on the page.
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
function prepareEventHandlers() {
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
//onfocus and onblur event handler illustration
var emailField = document.getElementById("email");
emailField.onfocus = function() {
if (emailField.value == "your email") {
emailField.value = "";
}
};
emailField.onblur = function() {
if (emailField.value == "") {
emailField.value = "your email";
}
};
}
window.onload = function() {
// preps everything and ensures
// other js functions don't get
// called before document has
// completely loaded.
prepareEventHandlers(); // This is a named function call nested inside an anonymous function.
}
//Sometimes we want js to run later or call a
// function in 60 seconds or every 5 sec, etc.
// Two main methods for timers: setTimeout and setInterval
// these timer functions are in milliseconds
var myImage = document.getElementById("mainImage");
var imageArray = ["images/Blue-roses.jpg", "images/Purple-Rose.jpg", "images/White-Rose.jpg", "images/orange-rose.jpg", "images/pink-roses.jpg", "images/red-roses.jpg", "images/yellow-roses.jpg", "images/murdock.jpg", "images/dorothy-red-ruby-slippers.jpg"];
var imageIndex = 0;
function changeImage(){
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
setInterval(changeImage, 5000);
//Sometimes we may want some random alert
// to pop up x-number of seconds later.
//So we use the setTimeout, like so:
/*function simpleMessage() {
alert("Get ready to learn!");
}
setTimeout(simpleMessage, 5000); */
/*var_dump($_POST);
if var_dump($_POST) = "";
return var($_GET);
error_log($_POST); */
If it's giving you that error, then it means that document.getElementById("email") evaluates to null, which means that no element exists with the id email.
That's all I can tell you without seeing the HTML that this JS is connected to.

Categories

Resources