So basically my code checks if an HTML element has the value of not 0, if it doesn't sets a timer to change the page title to a notification type of text.
I'm really, really new to JS, so I don't know why this did not work, I tried getElementById("licon liconspan") aswell, nothing.
EDIT: Okay, so I got this to work how I want it, here's the code:
function changeTitle() {
var title = document.title;
var variable = document.querySelector('.liconspan').innerHTML;
if ((variable) !== 0) {
setTimeout(changeTitle, 3000);
document.title = 'You have ' + variable + ' unread messages!';
}
}
changeTitle();
Question though, how can I make it switch back and forth with a title, for example "You got a message" for three seconds then "Page Title" for another three seconds then "You got a message" again, etc..
Since you are using jQuery you can get the element by class using a proper selector and check its value, to change the document title you don't need jQuery.
Alternatively you can use getElementsByClassName:
The Element.getElementsByClassName() method returns a live
HTMLCollection containing all child elements which have all of the
given class names. When called on the document object, the complete
document is searched, including the root node.
Code:
function changeTitle() {
var title = document.title;
if (parseInt($('.liconspan').val()) !== 0 ) {
setTimeout(changeTitle, 3000);
document.title='>'+title;
}
}
changeTitle();
Demo: http://jsfiddle.net/c9p670ra/
Related
For class, I'm trying to build a single page web page using jquery. One of the components of this is changing the HTML to find the correct ID to show the proper information needed.
I'm running into an issue where after the HTML is changed, the HTML is reverted to its original text. I've done some googling and I learned that it's reverting because of the page switch. Most of the questions already asked about this are dealing with form submissions so I'm not really sure how to deal with it in my case.
What I've tried already is having a global variable that keeps track of the ID but when I switch pages, the global variable also gets reset to its original value. I know that the value is getting reset because I have a console log of before and after.
function createList() {
let liArray = Array.from(document.getElementsByClassName("oneMusic"));
liArray.forEach(function (element) {
element.addEventListener("click", function () {
var parm = this.getAttribute("data-parm"); // passing in the record.Id
document.getElementById("IDparmHere").textContent = parm;
console.log(
"parm: " + document.getElementById("IDparmHere").innerHTML
);
param = parseInt(parm);
console.log("param" + param);
// now jump to our page that will use that one item
setTimeout(() => {
document.location.href = "index.html#details";
}, 1000);
});
});
}
And then the code that handles transferring pages. To note, param is the global var.
document.addEventListener("DOMContentLoaded", function (e) {
createList();
$(document).on("pagebeforeshow", "#details", function (event) {
console.log("param 2: " + param);
let localID = param;
let idx = GetArrayPointer(localID);
console.log("local id: " + localID);
console.log("arrayPointer: " + arrayPointer);
document.getElementById("oneTitle").innerHTML =
"The title is: " + songArray[idx].Song;
});
});
So the createList() does a bunch of things but at the end of it, it adds an event listener to each of the li elements. When you click on it, you pull the specific ID of that li and then you get transferred to the details page.
By the time the code reaches the details page, both the HTML and the global var revert back to their original values, which makes it useless in figuring out the ID.
For example, if #IDparmHere was changed from "blank" to "1", then after the page switch happens, #IDparmHere is changed back to "blank".
I set the global var as null initially, after it's changed from null to 1 or 2 or 3, after the page switch it goes back to null.
Also, parm is supposed to be "param" but the instructor that gave us the skeleton of this code has dyslexia so..
I have a JS file that goes to my database and return the value,
The only values that can exist are 0 and 1.
After this I go to an PHP file I invoke this value however I want create a if condition loop to analyze the value of this div for display an image depending of the value.
For example:
if (<div id="last_relay1"></div> = 0) then display IMAGE A
else
if (<div id="last_relay1"></div> = 1) then display IMAGE B
My difficulty is to use the value of as a PHP variable.
//Script to load the value of the current relay
$(document).ready(function(){
setInterval(function(){
$("#last_relay1").load('last_update.php #RELAY1_STATUS_last_update')
}, 1000);
});
//little code to display the value of LAST_RELAY1 for database.
//the values returned possibles are 0 and 1
<div id="last_relay1"></div>
You can use a callback function with .load() to check the text of the DIV after it has been loaded. Use .text() to get the contents of the DIV.
$("#last_relay1").load('last_update.php #RELAY1_STATUS_last_update', function() {
if ($this).text().trim() == "0") {
$("#image").prop("src", "imageA.png");
} else {
$("#image").prop("src", "imageB.png");
}
});
I think what you are looking to do is to send data from the web page (generated by JavaScript) to PHP to decide which image to serve.
The way you framed the question won't help you find a solution (http://xyproblem.info/).
Instead, you will need to either:
preload both image A and image b, and display the one you want in javascript by unhiding it.
Dynamically load the image using PHP by making an XHR request that returns the correct image.
I solved it. I follow the tip provided by Barmar.
I used the following code...
var value = $("#last_relay1").load('last_update.php #RELAY1_STATUS_last_update', function() {
var value_to_test = value.text();
if(value_to_test == 1){
$("#last_relay1").empty();
$('<img src="img/ON.png">').appendTo("#last_relay1"); }
else {
$('<img src="img/OFF.png">').appendTo("#last_relay1");
}
});
I'm attempting a make random quote machine with a tweet button to tweet the quote.
The random quote is coming up just fine.
The code..
var forismaticAPI = 'http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&lang=en&jsonp=?';
$(document).ready(function() {
var template = function(data) {
$('#quotearea').empty();
$('#quotearea').append('<blockquote id="quote">' + data.quoteText + '</blockquote>' + '<p id="author"> — ' + data.quoteAuthor + '</p>');
$('#quotearea').show();
};
var dataAppend = function() {
$.getJSON(forismaticAPI, template);
};
}
My next task is to get the quote content to be tweeted. So once the window loads completely i want to get the innerHTML of #quote which contains the quote. So i write a window.onload function like this..
window.onload = function(){
var quote = document.getElementById('quote');
console.log(quote.innerHTML);
}
But I'm getting an error Uncaught TypeError: Cannot read property 'innerHTML' of null(…).. Since there is small delay in loading the quote, the window load function returns a null. How to get the innerHTML of a div only when the content is loaded and ready?
Your #quote element is created after the window.onload event, because it's only created on the return of your ajax call. Move the code from onload to success of the ajax call, as BlueBoy suggested in comments. In your case, the success function is the one you named template.
You can access your element immediately after creating it:
var template = function(data) {
$('#quotearea').empty();
$('#quotearea').append('<blockquote id="quote">' + data.quoteText
+ '</blockquote>' + '<p id="author"> — ' + data.quoteAuthor + '</p>');
$('#quotearea').show();
console.log(document.getElementById('quote'));
};
You can't call the innerHTML method on DOM elements that do not exist yet. So the first moment you can run your function is after the append() call, which is creating a DOM element with and id of quote.
Without testing it, my guess is that onload is firing before the document ready. So you may want to 1) set a flag when the content has been written, Then 2) check in the second function, if null schedule it to run again in 100 ms using setTimeout().
use the html function?
var code = $('#quotearea').html();
I am trying to determine if an image source contains a string when I click on the image. The images have the class .swap-color. I have the variable $current_swatch set to the image src attribute, and it tests successfully. My code is below. No matter what image I click on, I get the alert "Contains TB", even if TB isn't in the image src. What am I doing wrong?
<img src="/images/Swatch-TB.jpg" class="swap-color"/>
$("document").ready(function () {
$('.swap-color').click(function () {
//get the image src
var $current_swatch = $(this).attr('src');
//check if TB is in the src
if ($('$current_swatch:contains("TB")').length > 0 ) {
alert ('Contains TB');
} else {
alert ('Does not contain TB');
}
});
});
There's enough feedback that I'm going to go out on a limb and post an answer, even though the key to your question could be done in a comment.
The way to check for the contents is to use the JS native indexOf(), rather than the jQuery selector method in your code.
Here's some commented revisions to your code:
// Streamlined, conflict-safe document ready
jQuery(function ($) {
$('.swap-color').click(function() {
//get the image src
var $current_swatch = $(this).attr('src');
//check if TB is in the src
// Use JS native "indexOf" rather than jQuery
if ($current_swatch.indexOf('TB') > -1 ) {
alert ('Contains TB');
} else {
alert ('Does not contain TB');
}
});
});
For more information on different ways to check for a substring, check out this answer: Fastest way to check a string contain another substring in Javascript?
So, you're using the jQuery's contains method which checks if a selector contains a value. The problem is, $current_swatch is actually a string, since $(this).attr('src') will give "/images/Swatch-TB.jpg".
Instead what you want is the vanilla JS includes.
if ($current_swatch.includes('TB')) {
...
I'll try to explain my problem with few words.
I have an HTML with various iframes. In one iframe there is a Table of Contents (TOC) and in an other the content of the corresponding element highlighted in the TOC. Since there are various TOCs, it might happen that by clicking on a link, we'll be taken to a topic which belongs to another TOC, and therefore I want the TOC frame to be reloaded with the proper TOC. To do so, since each topic has a unique id within the TOC, I perform a search of the id of the topic loaded in the main frame accross all the TOCs and when I find the wanted TOC, I load it in the TOC frame.
The code I've written so far is the seguent:
/*function called on load of each topic - it gets the topic unique id as parameter*/
function highlight(id) {
/*the names of the HTML files containing the different tocs*/
var tocs = ["toc.htm", "toc_documentazione.htm", "toc_flussiesteri.htm", "toc_garante.htm", "toc_legittimita.htm", "toc_normativa.htm", "toc_settori.htm", "toc_sicurezza.htm", "toc_sistemadp.htm", "toc_vistaarticolato.htm"]
var i = 0;
/*search within the different TOCs until you find a correspondence or there are no more TOCs*/
while (!changeTOC(tocs[i], "a" + id) && i < tocs.length) {
i = i + 1;
}
/*this line is probably wrong but the idea is to load the found TOC in the appropriate frame*/
$(content).load(tocs[i - 1] + " #content");
}
/*function using ajax to search the id into the HTML file passed as parameter (newToc) returning the search outcome*/
function changeTOC(newToc, id) {
var found = false;
$.get(newToc, "html").done(
function(temp_toc) {
/*if the HTML contains the id we search for we return true*/
if (temp_toc.indexOf(id) != -1)
found = true;
});
/*else we return false*/
return found;
}
The problem I have is with the while cycle I use to search through the various TOC files. I did some debugging and, regardless from the fact the TOC containing the id I'm searching for is at the first position, the while extecutes 10 cycles and only at the very last it tells me that it has found the matching TOC, which is indeed the first one in the list.
Hope I've been able to make myself clear.
Thanks for your help
I finally managed to get this done by using the ajax call with syncronus set to true. I'm not posting here all the code cause it would be confusing, but below is what I changed compared to the code written above and now everything works just fine. Maybe it's not optimal in terms of performance but I don't have this concern, so I'm happy with it :)
Hope this can help others.
/*function called on load of each topic - it gets the topic unique id as parameter*/
function highlight(id) {
var tmpVal = sessionStorage.getItem('key');
//we check if there is another element in the TOC currently highlighted in bold, if so we remove the highlight
if(tmpVal) {
var tmpEle=parent.window.frames[0].document.getElementById('a'+tmpVal);
if (tmpEle) {
tmpEle.className='';
}
}
//loop through all TOCs to find the one containing the selected topic
var tocs = ["toc.htm","toc_documentazione.htm","toc_flussiesteri.htm","toc_garante.htm","toc_legittimita.htm","toc_normativa.htm","toc_settori.htm","toc_sicurezza.htm","toc_sistemadp.htm","toc_vistaarticolato.htm"];
var i=0;
while (!changeTOC(tocs[i],"a"+id)&&i<tocs.length){
i=i+1;
}
//get currently loaded TOC
var currentToc=$("#toc_iframe",parent.document).attr("src");
var indexCurrentTOC=tocs.indexOf(currentToc);
//we check if the matching TOC is the current one, if so we don't change anything
if(!changeTOC(tocs[indexCurrentTOC],"a"+id)){
$("#toc_iframe",parent.document).attr("src",tocs[i]);
}
var myElt=parent.window.frames[0].document.getElementById('a'+id);
//highlight current element in the TOC
myElt.focus();
myElt.className+=' active';
scrollTo(myElt.offsetLeft-48, myElt.offsetTop-(parent.document.body.clientHeight/3));
sessionStorage.setItem("key", id);
}
//searches for the element with given id into the toc file newToc
function changeTOC(newToc,id){
var found = false;
$.ajax({
url: newToc,
async: false,
context: document.body
}).done(function(temp_toc) {
if(temp_toc.indexOf(id)!=-1){
found = true;
}
});
return found;
}