I'm trying to run a bit of code to flash the favicon back and forth between 2 .ico's indefinitely every second. So far I've got this code which changes it once, but not again;
var favUrl = "favicon.ico";
var flashFavIco = function() {
if(favUrl == "favicon.ico") {
favUrl = "favicon-white.ico";
} else {
favUrl = "favicon.ico";
}
console.log(favUrl);
var link = document.createElement('link');
link.type = 'image/x-icon';
link.rel = 'shortcut icon';
link.href = 'http://www.mysite.com/' + favUrl;
document.getElementsByTagName('head')[0].appendChild(link);
};
setInterval(flashFavIco, 1000);
I tested adding console.log()s in the if/else sections to check that favURL was being set each second, which it was indeed. So I'm a little stuck as to why the favicon only changes once. Is this a browser issue?
Edit: I do realise this continually adds new <link ... tags to the head, and I'm working on writing that appendChild part differently, this does not affect my original question
I re-wrote part of it and now have it working;
var favUrl = "favicon.ico";
var link = document.createElement('link');
link.type = 'image/x-icon';
link.rel = 'shortcut icon';
link.href = 'http://www.mysite.com/' + favUrl;
link.id = "favico";
document.getElementsByTagName('head')[0].appendChild(link);
var flashFavIco = function() {
if(favUrl == "favicon.ico") {
favUrl = "favicon-white.ico";
} else {
favUrl = "favicon.ico";
}
$('#favico').prop('href', 'http://www.mysite.com/' + favUrl);
};
setInterval(flashFavIco, 1000);
Rewrote it for you.
// Edit these
var faviconNormal = "/faviconNormal.ico";
var faviconActive = "/faviconActive.ico";
var faviconID = "#myfavicon"; // CSS selector for your <link> element
// Declarations
var faviconElement = document.querySelector(faviconID);
var faviconIsActive = false;
function flashFavicon() {
if (faviconIsActive == false) {
changeFavicon(faviconActive);
faviconIsActive = true;
}
else {
changeFavicon(faviconNormal);
faviconIsActive = false;
}
}
function changeFavicon(src) {
faviconElement.href = src;
}
// Run
var initFlashing = setInterval(flashFavicon, 1000);
Related
(function () {
// Creating and Appending scripts dynamically
function createScript(src) {
var script = document.createElement('script');
script.src = src;
document.getElementsByTagName('head')[0].appendChild(script);
}
// End script tags Here
function createLink(href) {
var link = document.createElement('link');
link.href = href;
link.rel = "stylesheet";
link.type = "type/css";
document.getElementsByTagName('head')[0].appendChild(link);
}
createLink('http://vjs.zencdn.net/4.12/video-js.css');
createScript('http://vjs.zencdn.net/4.12/video.js');
createLink('http://localhost/projects/test/bin/videojs.vast.vpaid.min.css');
createScript('http://localhost/projects/test/bin/videojs_4.vast.vpaid.min.js');
createScript('http://localhost/projects/test/bin/es5-shim.js');
createScript('http://localhost/projects/test/bin/ie8fix.js');
// DIV 2
// Div to hold the video
var divContainer = document.createElement('div');
divContainer.class = 'example-video-container';
divContainer.style.display = 'inline-block';
document.getElementById("video3438445[CB]").appendChild(divContainer);
// End parent Div here (parent of video div/tag)
// Video Player Below
// Create the video tag for html video player
var video = document.createElement('video');
video.id = 'video';
/*video.width = 300;
video.height = 250;*/
video.className = 'video-js vjs-default-skin';
video.autoplay = true;
video.controls = true;
video.muted = true;
video.preload = 'auto';
video.poster = "http://vjs.zencdn.net/v/oceans.png";
//video.data-setup = '{}';
// Function to create sources for video
function addSourceToVideo(element, src, type) {
var source = document.createElement('source');
source.src = src;
source.type = type;
element.appendChild(source);
}
addSourceToVideo(video, 'http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4', 'video/mp4');
addSourceToVideo(video, 'http://video-js.zencoder.com/oceans-clip.mp4', 'video/webm');
addSourceToVideo(video, 'http://video-js.zencoder.com/oceans-clip.mp4', 'video/ogg');
var paragraph = document.createElement('p');
paragraph.innerHTML = "Video PlayBack Not Supported";
video.appendChild(paragraph);
video.load();
//video.play();
divContainer.appendChild(video);
// Video player creation ends here
var vt = 'Vast_tag_url';
var vpaidPath = 'http://localhost/projects/test/bin/VPAIDFlash.swf';
setTimeout(myFunction, 1000);
function myFunction() {
var player = videojs(
"video", {
plugins: {
"vastClient": {
"adTagUrl": vt,
"adCancelTimeout": 15000,
"adsEnabled": true,
"playAdAlways": true,
"vpaidFlashLoaderPath": vpaidPath
}
}
})
}
})();
It works on normal HTML page when we have CSS and JS in head then a div with video and JS functions in body. But when I created a JS file and included it by javascript then it is not working.
Please suggest me what I am doing wrong.
Thanks so much for your response. My issue has been resolved. I used following code for this.
function loadScriptSync(src) {
var s = document.createElement('script');
s.src = src;
s.type = "text/javascript";
s.async = false; // <-- this is important
document.getElementsByTagName('head')[0].appendChild(s);
}
It will load js files synchronously.
The way you are loading the scripts is asynchronously.
You could either load them in the head directly, or implement a method that will listen to the loading events. Example below written in ES6.
function loadScript(src) {
return new Promise((onFulfilled, onRejected) => {
const script = document.createElement('script');
let loaded;
// set source path to load
script.setAttribute('src', src);
script.onreadystatechange = script.onload = () => {
if (!loaded) {
onFulfilled(script);
}
loaded = true;
};
script.onerror = function() {
// something went wrong
};
// append the given script
document.getElementsByTagName('head')[0].appendChild(script);
});
}
loadScript('http://url').then(() => {
// do something now that the script is loaded.
});
Now you will be sure that when the promise is fulfilled, the script is loaded successfully.
I was implementing some audio files today in my Javascript and it works fine. But
I noticed that with each subsequent click the sound gets louder. I alreadio used the "Audio.volume" method but no luck.
My Code:
var AppController = (function () {
var correctItem, secondItem, thirdItem, selectedItems, selectedItemsShuffled;
var rotateImage = function() {
var i = 0;
var randomNumbers = createThreeRandomNumbers();
var interval = window.setInterval(function () {
i++;
document.getElementById("imageToRotate").src= "img/" + items.images[i].imageLink;
if (i === items.images.length -1) {
i = -1;
}
}, 125);
var clearData = function () {
correctItem = "";
secondItem = "";
thirdItem = "";
selectedItems = "";
selectedItemsShuffled = "";
removeNodeChildren("button-1");
removeNodeChildren("button-2");
removeNodeChildren("button-3");
};
var removeNodeChildren = function (obj) {
var myNode = document.getElementById(obj);
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
};
var resetGame = function () {
clearData();
document.getElementById("buttonWrapper").classList.remove("show");
rotateImage();
}
document.getElementById("imageToRotate").addEventListener("click", function (e) {
// select 3 items
correctItem = getSelectedItemDetails(e);
secondItem = getRandomItem(correctItem);
thirdItem = getSecondRandomItem(correctItem, secondItem);
selectedItems = [correctItem, secondItem, thirdItem];
selectedItemsShuffled = shuffleArray(selectedItems);
// create the numbers 1 to 3 randomly
var order = createThreeRandomNumbers();
// remove the rotating effect
clearInterval(interval);
// set the images to the buttons in a random order.
setItemsToButtons(order, selectedItemsShuffled);
//show the buttons
showButtons();
// Create an event which triggers when a button is clicked.
document.getElementById("buttonWrapper").addEventListener("click", function(e) {
var valueOfButtonPressed = e.srcElement.innerText.toLowerCase();
var clickedButton = e.srcElement.id;
if (valueOfButtonPressed === correctItem) {
document.getElementById(clickedButton).innerHTML = e.srcElement.innerText.toLowerCase() + '<span class="icon"><i class="fa fa-check green" aria-hidden="true"></i></span>';
if (!audio) {
var audio = new Audio("audio/correct.mp3");
}
audio.play();
audio.volume = 0.5;
setTimeout(resetGame, 5000);
} else {
document.getElementById(clickedButton).innerHTML = e.srcElement.innerText.toLowerCase() + '<span class="icon"><i class="fa fa-times red" aria-hidden="true"></i></span>';
if (!audio) {
var audio = new Audio("audio/wrong.mp3");
}
audio.play();
audio.volume = 0.5;
setTimeout(resetGame, 5000);
}
});
});
};
// 1: hide the buttons
hidebuttons();
// 2: Replace the title
replaceTitle("Animals");
// 3: set up image rotation until it's clicked.
rotateImage();
})();
Any help will be much appreciated. Cheers!
I'm fairly certain the reason is that you're making a new Audio object with every single click.
Instead of doing this with every click:
var audio = new Audio("audio/correct.mp3");
do a check to see if audio already exists. if it does, then simply do audio.play(). If it does not, THEN you make a new audio object.
So i am trying to make it so if you click on the button it will switch the images placement. However it doesnt actually switch the placement but instead just changes the src of each image ID. It works when you click the button once, but after that the images no longer switch. This is my code
function swapImages(){
var image1 = document.getElementById("image1")
var image2 = document.getElementById("image2")
if (image1.src = '/jmurphy9/111/images/earthrise.jpg') {
image1.src = '/jmurphy9/111/images/earth.jpg';
} else {
image1.src = '/jmurphy9/111/images/earthrise.jpg';
}
if (image2.src = '/jmurphy9/111/images/earth.jpg') {
image2.src = '/jmurphy9/111/images/earthrise.jpg';
} else {
image2.src = '/jmurphy9/111/images/earth.jpg';
}
}
function init(){
var button1 = document.getElementById("btn1")
button1.onclick = swapImages;
}
window.onload = init;
The problem is the src property will have the absolute path to the image, not relative one as you are checking
One possible solution is to use .indexOf() as given below
function swapImages() {
var image1 = document.getElementById("image1")
var image2 = document.getElementById("image2")
if (image1.src.indexOf('/jmurphy9/111/images/earthrise.jpg')>-1) {
image1.src = '/jmurphy9/111/images/earth.jpg';
} else {
image1.src = '/jmurphy9/111/images/earthrise.jpg';
}
if (image2.src.indexOf( '/jmurphy9/111/images/earth.jpg')>-1) {
image2.src = '/jmurphy9/111/images/earthrise.jpg';
} else {
image2.src = '/jmurphy9/111/images/earth.jpg';
}
}
Or you can use .getAttribute()
if (image1.getAttribute('src') == '/jmurphy9/111/images/earthrise.jpg') {
}
But since you want to swap, you can just do
function swapImages() {
var image1 = document.getElementById("image1")
var image2 = document.getElementById("image2")
var src = image1.src;
image1.src = image2.src;
image2.src = src;
}
Demo: Fiddle
Note: In your if condition you are using assignment(=) operator instead of comparison operator(==), so image1.src = '/jmurphy9/111/images/earthrise.jpg' in the if should be image1.src == '/jmurphy9/111/images/earthrise.jpg'
Looks like your equality operator is missing an extra "=" on your if's e.g. if(image1.src == '/jmurphy9/111/images/earthrise.jpg') so when it tries to evaluate the expression it never goes in so it changes the first time 'cause it goes to the else and from there on it just keeps going to the else so nothing happens.
function swapImages(){
var image1 = document.getElementById("image1")
var image2 = document.getElementById("image2")
if (image1.src == '/jmurphy9/111/images/earthrise.jpg') {
image1.src = '/jmurphy9/111/images/earth.jpg';
} else {
image1.src = '/jmurphy9/111/images/earthrise.jpg';
}
if (image2.src == '/jmurphy9/111/images/earth.jpg') {
image2.src = '/jmurphy9/111/images/earthrise.jpg';
} else {
image2.src = '/jmurphy9/111/images/earth.jpg';
}
}
function init(){
var button1 = document.getElementById("btn1")
button1.onclick = swapImages;
}
window.onload = init;
The accepted answer, like yours, swaps the src attribute of the images.
Another method is to actually swap the img nodes themselves, which may be preferable if the images matter severally- eg., need special event handling or css considerations that depend on the actual image.
function swapNodes(a, b){
var p= b.parentNode, sib= b.nextSibling;
if(sib=== a) sib= sib.nextSibling;
a.parentNode.replaceChild(b, a);
return sib? p.insertBefore(a, sib): p.appendChild(a);
}
note that you can always swap img nodes, or any two like nodes, but there are some nodes that cannot be swapped, because the container node of one will not accept the other as a child.
You can swap them if they make valid html.
I'm using the javascript from this older script: JavaScript: how to load all images in a folder?
However, I want to use the same javascript file to write some html code before the loop and some after the loop, all using this same javascript file.
Just putting a document.write before and after it in the javascript doesn't work.
var bCheckEnabled = true;
var bFinishCheck = false;
var img;
var imgArray = new Array();
var i = 0;
var myInterval = setInterval(loadImage, 1);
function loadImage() {
if (bFinishCheck) {
clearInterval(myInterval);
document.write('Loaded ' + i + ' image(s)');
return;
}
if (bCheckEnabled) {
bCheckEnabled = false;
img = new Image();
img.onload = fExists;
img.onerror = fDoesntExist;
img.src = 'assets/' + i + '.png';
document.write('<img src="assets/' + i + '.png" width="1016" height="813" alt="Kar" />');
}
}
function fExists() {
imgArray.push(img);
i++;
bCheckEnabled = true;
}
function fDoesntExist() {
bFinishCheck = true;
}
You may be using this example code incorrectly. Its intent appears to be to pre-load the image files in the background, not display them to the user in the HTML (yet). This is to improve apparent download speed of your page.
In short, this code doesn't actually render the image into the DOM; and that is intentional behavior.
I have a class, that is supposed to display grey overlay over page and display text and loading gif. Code looks like this:
function LoadingIcon(imgSrc) {
var elem_loader = document.createElement('div'),
elem_messageSpan = document.createElement('span'),
loaderVisible = false;
elem_loader.style.position = 'absolute';
elem_loader.style.left = '0';
elem_loader.style.top = '0';
elem_loader.style.width = '100%';
elem_loader.style.height = '100%';
elem_loader.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
elem_loader.style.textAlign = 'center';
elem_loader.appendChild(elem_messageSpan);
elem_loader.innerHTML += '<br><img src="' + imgSrc + '">';
elem_messageSpan.style.backgroundColor = '#f00';
this.start = function () {
document.body.appendChild(elem_loader);
loaderVisible = true;
};
this.stop = function() {
if (loaderVisible) {
document.body.removeChild(elem_loader);
loaderVisible = false;
}
};
this.setText = function(text) {
elem_messageSpan.innerHTML = text;
};
this.getElems = function() {
return [elem_loader, elem_messageSpan];
};
}
Problem is, when I use setText method, it sets innerHTML of elem_messageSpan, but it doesn't reflect to the span, that was appended to elem_loader. You can use getElems method to find out what both elements contains.
Where is the problem? Because I don't see single reason why this shouldn't work.
EDIT:
I call it like this:
var xml = new CwgParser('cwg.geog.cz/cwg.xml'),
loader = new LoadingIcon('./ajax-loader.gif');
xml.ondataparse = function() {
loader.stop();
document.getElementById('cover').style.display = 'block';
};
loader.setText('Loading CWG list...');
loader.start();
xml.loadXML();
xml.loadXML() is function that usually takes 3 - 8 seconds to execute (based on download speed of client), thats why I'm displaying loading icon.