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

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();

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]);
});
});
}

How to exchange counter after delete field using plain javascript

I'm new in javascript. i have a JS function that add and remove input fields. its working fine with my JS function. But I want when delete a field its Id looks like:
I have
no. 1
no. 2
no. 3
After Delete 2:
no. 1
no. 2
already i got this answer:
Reset JavaScript Counter after Deleting a field
But i want it with plain javascript. Can anyone help?
<script>
var count = 1;
function add_new(){
count++;
var div1 = document.createElement('div');
div1.id = count;
var delLink = '<button type="button" onclick="deleteLink('+count+')" class="btn btn-primary">Delete</button>';
div1.innerHTML = document.getElementById('add_link1').innerHTML+delLink;
document.getElementById('add_link').appendChild(div1);
document.getElementById("input_link1").id = count;
document.getElementById("input_link2").id = count;
document.getElementById("input_link3").id = count;
}
function deleteLink(eleId){
var ele = document.getElementById(eleId);
var par = document.getElementById('add_link');
par.removeChild(ele);
}
</script>
After deleting an element call the following function to reset Id of existing elements and also reduce the count.
function reset_counter(deletedCount) {
for (var impactedElementId = deletedCount + 1; impactedElementId < count; impactedElementId++) {
var currentElement = document.getElementById(impactedElementId);
currentElement.id = impactedElementId - 1;
var button = currentElement.firstChild;
button.innerHTML = 'Delete ' + currentElement.id;
button.setAttribute('onclick', 'deleteLink(' + currentElement.id + ')');
}
count--;
}
The full code is available here: AddDeleteElements Sample Code

button onclick not working on first click

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.

Cant call Jquery function in if loop

my first ever question pretty sure I'm being a bit daft here, but am a beginner and would appreciate your help.
Im working on a webpage where there is a html table listing several columns of data.
When the page loads it runs a jquery script which counts the different types of "incidents" and plots them in another table which then another jquery script populates a graph.
I have a third script (javascript) which after a button is clicked, runs an if loop, which looks at the data in the first column and if it does not match the criteria then the row is deleted.
So far so good, the issue is that I want the script which populates the table for the graph to run again, but Im not sure how to call it from my if loop.
Ive put the two scripts below, basically I want to call the 1st script in the second script.
$(function () {
var NumFireAlarms = $("#incidents tr:contains('Fire Alarm')");
$("#result").html(NumFireAlarms.length + " Fire Alarm");
var firealarms = NumFireAlarms.length;
document.getElementById("no_of_incident_type").rows[1].cells[1].innerHTML = firealarms
var NumLockout = $("#incidents tr:contains('Lockout Out of Office Hours')");
$("#result").html(NumLockout.length + " Lockout Out of Office Hours");
var lockouts = NumLockout.length;
document.getElementById("no_of_incident_type").rows[2].cells[1].innerHTML = lockouts
var NumLockoutDayTime = $("#incidents tr:contains('Lockout Day Time')");
$("#result").html(NumLockout.length + " Lockout Day Time");
var lockoutsDayTime = NumLockoutDayTime.length;
document.getElementById("no_of_incident_type").rows[3].cells[1].innerHTML = lockoutsDayTime
var NumSensitiveIncident = $("#incidents tr:contains('Sensitive Incident')");
$("#result").html(NumSensitiveIncident.length + " Sensitive Incident");
var SensitiveIncident = NumSensitiveIncident.length;
document.getElementById("no_of_incident_type").rows[4].cells[1].innerHTML = SensitiveIncident
});
function filterForGraph() {
var incident_category = document.getElementById("Incident_Category").value;
var start_date = document.getElementById("start_date").value;
var end_date = document.getElementById("end_date").value;
var staff_type = document.getElementById("Job_Title").value;
var i;
var count = 0;
var table_length = document.getElementById("incidents").rows;
var TL = table_length.length;
for (i = TL - 1; i >= 1; i--)
{
var category_column = document.getElementById("incidents").rows[i].cells.item(0).innerHTML;
var date_column = document.getElementById("incidents").rows[i].cells.item(1).innerHTML;
var staff_colunm = document.getElementById("incidents").rows[i].cells.item(8).innerHTML;
if (category_column === incident_category)
{
alert("yay")
count++
}
else if (category_column !== incident_category)
{
alert("boo")
document.getElementById("incidents").deleteRow(i);
//CALL FIRST SCRIPT HERE??
}
}
}
I removed a few bits of code that did not seem to do anything, but I'm sure you can put them back. I think you might want something like this:
function updateTable(){
var elResult = document.getElementById("result");
var elNumIncidentType = document.getElementById("no_of_incident_type");
var firealarms: document.querySelectorAll("#incidents tr:contains('Fire Alarm')").length;
var lockouts: document.querySelectorAll("#incidents tr:contains('Lockout Out of Office Hours')").length;
var lockoutsDayTime: document.querySelectorAll("#incidents tr:contains('Lockout Day Time')").length;
var sensitiveIncident: document.querySelectorAll("#incidents tr:contains('Sensitive Incident')").length;
elResult.innerHTML = "";
elResult.innerHTML += "<div>" + firealarms + " Fire Alarm</div>";
elResult.innerHTML += "<div>" + lockouts + " Lockout Out of Office Hours</div>";
elResult.innerHTML += "<div>" + lockoutsDayTime + " Lockout Day Time</div>";
elResult.innerHTML += "<div>" + sensitiveIncident + " Sensitive Incident</div>";
elNumIncidentType.rows[1].cells[1].innerHTML = firealarms;
elNumIncidentType.rows[2].cells[1].innerHTML = lockouts;
elNumIncidentType.rows[3].cells[1].innerHTML = lockoutsDayTime;
elNumIncidentType.rows[4].cells[1].innerHTML = sensitiveIncident;
}
function filterForGraph() {
var elIncidents = document.getElementById("incidents");
var incident_category = document.getElementById("Incident_Category").value;
var table_length = document.getElementById("incidents").rows.length;
for (var i = table_length - 1; i >= 1; i--) {
var currentIncident = elIncidents.rows[i].cells;
var category_column = currentIncident.item(0).innerHTML;
if (category_column != incident_category) { elIncidents.deleteRow(i); }
}
updateTable();
}
$(function(){ updateTable(); });
Hi JonSG tried your code and it didnt work not sure why, but it gave me some ideas to work with and I think Ive cracked it
function Populate_Incident_No_Table() {
//previously function called updateTable
$(function () {
var NumFireAlarms = $("#incidents tr:contains('Fire Alarm')").length;
document.getElementById("no_of_incident_type").rows[1].cells[1].innerHTML = NumFireAlarms
var NumLockout = $("#incidents tr:contains('Lockout Out of Office Hours')").length;
document.getElementById("no_of_incident_type").rows[2].cells[1].innerHTML = NumLockout
var NumLockoutDayTime = $("#incidents tr:contains('Lockout Day Time')").length;
document.getElementById("no_of_incident_type").rows[3].cells[1].innerHTML = NumLockoutDayTime
var NumSensitiveIncident = $("#incidents tr:contains('Sensitive Incident')").length;
document.getElementById("no_of_incident_type").rows[4].cells[1].innerHTML = NumSensitiveIncident
});
}
function filterForGraph() {
var incident_category = document.getElementById("Incident_Category").value;
var i;
var TL = document.getElementById("incidents").rows.length;
for (i = TL - 1; i >= 1; i--)
{
var category_column = document.getElementById("incidents").rows[i].cells.item(0).innerHTML;
if (category_column !== incident_category)
{
document.getElementById("incidents").deleteRow(i);
}
}
Populate_Incident_No_Table();
drawGraph();
}
I think the issue was how I was trying to call the functions. So what I've done to achieve what I wanted (please excuse any bad terminology / phrasing).
First I tried to name the function $(function updateTable(){ this did not work when I then tried to call the function like this updateTable();
Second thing I tried was putting the updateTable() function "inside" a function and call that function. This has worked for me I dont know why.
Thanks for your help without it I would not have thought to try what I did

How to change the value of the variable in this function without making a new function

function SlideShow(area) {
var SlideImg = new Array('img1', 'img2');
var SlideArea = document.getElementById(area);
for (i = 0; i < SlideImg.length; i++) {
if (SlideImg[i] == SlideImg[0]) {
var classname = 'active';
} else {
var classname = 'not-active';
}
var html = '<img src="images/room/' + SlideImg[i] + '.jpg" id="' + SlideImg[i] + '" class="' + classname + '" />';
SlideArea.innerHTML += html;
}
var a = 1;
function RunSlide() {
var before = a - 1;
if (a > SlideImg.length - 1) {
a = 0;
}
ImgBefore = document.getElementById(SlideImg[before]);
ImgBefore.className = 'not-active';
ImgNext = document.getElementById(SlideImg[a]);
ImgNext.className = 'active';
a++;
}
var run = setInterval(RunSlide, 5000);
}
How to change the a value? Because the a variable is not in the Global scope, can I access it from another function?
I want to access it, but don't want to declare the a variable as a global.
Yes, the variable is local to the function, so you have to expose a function outside to be able to access it.
You can for example put this last in the function to make it return a function that can set the variable:
function SlideShow(area) {
...
return function(value){ a = value; };
}
Usage:
var setA = SlideShow(something);
Then later you can use the function:
setA(42);
Simple, declare var a; outside of SlideShow and then it will be globally accessible.
Remember that it will still require resetting within the functin with a = 1;
If you can make the scope of the a variable global, then you should be able to. Instead of declaring in your function, just reference variable and declare in the "< head >" of your page instead. See my example and this I tested and clicking diff links changes value of variable and displays on page.
<html>
<head><title>Test</title>
<script language="javascript">
var a = -1;
function changeVar(value) {
a = value;
document.getElementById("test1").innerHTML = a;
}
</script>
</head>
<body>
<h1>Test page</h1>
Click me (2) <br />
Click me (5) <br />
Click me (9) <br />
<hr>
<h1>Value for a is: <div id="test1"></div></h1>
<!-- really test by including function later on page -->
<script language="javascript">
function SlideShow(area) {
var SlideImg = new Array('img1', 'img2');
var SlideArea = document.getElementById(area);
for (i = 0; i < SlideImg.length; i++) {
if (SlideImg[i] == SlideImg[0]) {
var classname = 'active';
} else {
var classname = 'not-active';
}
var html = '<img src="images/room/' + SlideImg[i] + '.jpg" id="' + SlideImg[i] + '" class="' + classname + '" />';
SlideArea.innerHTML += html;
}
a = 1; // removed declaration of a and just using a from prior declaration
function RunSlide() {
var before = a - 1;
if (a > SlideImg.length - 1) {
a = 0;
}
ImgBefore = document.getElementById(SlideImg[before]);
ImgBefore.className = 'not-active';
ImgNext = document.getElementById(SlideImg[a]);
ImgNext.className = 'active';
a++;
}
var run = setInterval(RunSlide, 5000);
}
</script>
</html>
You cannot access the variable itself if declared in the function because it's scope is LOCAL. See: http://www.w3schools.com/js/js_variables.asp
However, there is a way you could tweak your function to set a value of another element on the page, then others can reference that value. Using same code snippet for your script, when a is updated you can set the value of a hidden field on your page, and then others can reference that value. Any other way I think you have to declare it outside the function.
ALTERNATE 1:
<!-- really test by including function later on page -->
<script language="javascript">
function SlideShow(area) {
var SlideImg = new Array('img1', 'img2');
var SlideArea = document.getElementById(area);
for (i = 0; i < SlideImg.length; i++) {
if (SlideImg[i] == SlideImg[0]) {
var classname = 'active';
} else {
var classname = 'not-active';
}
var html = '<img src="images/room/' + SlideImg[i] + '.jpg" id="' + SlideImg[i] + '" class="' + classname + '" />';
SlideArea.innerHTML += html;
}
var a = 1;
function RunSlide() {
var before = a - 1;
if (a > SlideImg.length - 1) {
a = 0;
}
ImgBefore = document.getElementById(SlideImg[before]);
ImgBefore.className = 'not-active';
ImgNext = document.getElementById(SlideImg[a]);
ImgNext.className = 'active';
a++;
// set value of element on page so others can reference
document.getElementById("test1").innerHTML = a; // or set a hidden field
}
var run = setInterval(RunSlide, 5000);
}
</script>
The other way you might be able to do it is declare a return for your function with the value of a, and callers can ignore it if they want and others can retrieve it. This may not work with your setTimeOut re-calling the RunSlide function. I tried another inner function within SlideShow but that didn't seem to return a either. Original scoping suggestion remains.

Categories

Resources