Rotating font family with js - javascript

I'm very new to JS, I have a problem that could easily be solved I think but I can't figure it out :
I would like to find a way to change the font-family of an html element every 0.1 seconds without having to trigger something.
Basically I would like the html element to change font every 0.1 sec, rotating amongst 6 font families.
really thankful if you guys can find a way.
Louis

Try something like :
function changefontFamily() {
var doc = document.getElementById("elementID");
var font= ["Arial", "Verdana", "Helvetica ", "Tahoma"];
doc.style.fontFamily= font[i];
i = (i + 1) % font.length;
}
setInterval(changefontFamily, 100);
<div id="elementID">text</div>

I set 1 second (1000 ms), for clarity, because 100ms is too fast 🙂
(async()=>{
const elem = document.getElementById('elementID');
const fonts = ['Arial', 'Tahoma', 'Verdana'];
let k = fonts.length;
setInterval(()=>{
k--;
elem.style.fontFamily = fonts[k];
console.log('Now:', fonts[k], k);
if(k === 0)k = fonts.length;
}, 1000);
})();
<div id="elementID">Some Text to test it OUT</div>

Related

Interpolation (fading) between two colors in JavaScript

I have a project in which I have to modify code to fade the background color of a piece of text between two different colors, or like rotate between them using their RGB values. But I have no clue how to accomplish this, we are told to use requestAnimationFrame and a clock essentially to make this happen. Attached I will have the code which I need to modify. At present, the code just blinks between white and red, and as I said, it needs to fade between the two, more like a pulse or a throb if you will.
function makeThrob(id, rate, blinkColors) {
rate = rate ? rate : 1000;
blinkColors = blinkColors ? blinkColors : ["red","white"];
let toblink = document.getElementById(id);
let lastBlinkTime = 0;
let lastBlinkColor = 0;
function blinker(time) {
if ((time-lastBlinkTime) > rate) {
lastBlinkTime = time;
toblink.style.backgroundColor =
blinkColors[lastBlinkColor % blinkColors.length];
lastBlinkColor++;
}
window.requestAnimationFrame(blinker);
}
window.requestAnimationFrame(blinker);
}
makeThrob("ex3-span");

My script for page loading bar, returns differently everytime of F5

I got a free source progress bar, and I wrote a script for it.
the script is here,
var nanobar = new Nanobar( options );
var loaded = 0;
var number_of_media = $("body img").length;
doProgress();
// function for the progress bar
function doProgress() {
$("img").load(function() {
loaded++;
var newWidthPercentage = (loaded / number_of_media) * 100;
nanobar.go(newWidthPercentage);
document.getElementById("showing").innerHTML = newWidthPercentage;
})
};
});
This. I think,
Loaded <-- (which gets + 1 every time an image finished loaded)
divided by
Number of total body images,,
and then multiplied by 100
So that this can make the percentage number of loading process.
Then I put that percentage number into the box of,
A Loading bar's destination point. (which is : nanobar.go( here ))
But the bar moves werid,
everytime I click the menu, it returns different.
so I made a box to display the percentage number ( in the red box you can see in the picture )
I don't understand how this kind of random numbers are coming out every time.
Please advice.
Consider....
6/7 = 0.8571428571;
0.8571428571 * 100 = 85.71428571;
So if you want to 'tidy' these long decimals, then you need to truncate the float. http://www.w3schools.com/jsref/jsref_tofixed.asp
var num = 0.8571428571 * 100;
var n = num.toFixed(2);
Then n == 85.71
I hope this helps.

JavaScript filter hueRotate does not work

I am trying to change an image's (#bgImage) hue when hovering over a button (profIcon) in JavaScript. This type of button is created with JS, and there are 9 of them.
Here is the code that creates a DOM image element, sets it's source, position, size and transition. Finally it appends it to it's container. The image appears correctly, where it should be.
I am using quickID in place of document.getElementById, and it is working without error.
var bgImage = document.createElement("img");
bgImage.id = "bgImage";
bgImage.src = "./resources/images/backgrounds/profession/selector.jpg";
bgImage.style.position = "absolute";
bgImage.style.left = "0px";
bgImage.style.top = "0px";
bgImage.style.width = "100%";
bgImage.style.height = "100%";
bgImage.style.zIndex = 1;
bgImage.style.webkitTransition = "all 0.5s ease";
quickID("centerdiv").appendChild(bgImage);
Here is the code that runs when I hover over an image:
profIcon.onmouseover = function () {
var thisNr = this.id.substr(8); //last char of the profIcon ID; number between 0 and 8
var newHue = profTomb[thisNr][3]; //this contains the value and only that.
console.log(newHue); //always returns the correct value
quickID(this.id).style.webkitFilter = "grayscale(0%)"; //this part works, too
quickID("bgImage").style.webkitFilter = "hueRotate(" + newHue + "deg)";
}
My problem: for some reason, the filter does not apply. newHue is either a positive (75), or a negative (-23) value and it's inserted correctly, as it appears in the console log. I only use webkit vendor prefix as I use Google Chrome.
I waited up to 1 minute with my mouse cursor over the image, thinking my system needs time to process the transformation, but nothing happened.
Does anyone knows what is the problem?
The correct string to use is hue-rotate, not hueRotate. The following should work:
quickID("bgImage").style.webkitFilter = "hue-rotate(" + newHue + "deg)";

Change HTML Background randomly on page refresh

I know this topic has been looked at loads of times, but I would like my home page to randomly select an image and then change the subtitle for that image. The URL for my site is: http://www.connorloughlin.com
At the bottom of the page is a little subtitle, would be great if it changed for the relevant background. If it's too complex I won't bother but thought it'd look good! Preferably i'd have 5 images each with their own subtitle.
Let me know if you want me to clarify anything and thanks in advance!
Since you're using jQuery, I've made a version using that: http://jsbin.com/OQugAMI/4/edit
1) create an Array containing the list of images & subtitles
var backgrounds = [
{ image: 'http://www.connorloughlin.com/images/background.jpg',
subtitle: 'Looking out at Carcassonne, France - August 2013'
},
{ image: 'http://upload.wikimedia.org/wikipedia/commons/1/13/1632x1224_sertaoe_2_rio_grande_do_norte_landscape_panorama_brasil.jpg',
subtitle: 'Version 2'
},
{ image: 'http://upload.wikimedia.org/wikipedia/commons/7/71/1632x1224_sertaoe_rio_grande_do_norte_landscape_panorama_brasil.jpg',
subtitle: 'Version 3'
}
];
2) select a random image from that array
/**
* Returns a random integer between min and max
* Using Math.round() will give you a non-uniform distribution!
* http://stackoverflow.com/questions/1527803/generating-random-numbers-in-javascript-in-a-specific-range
*/
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
$(document).ready(function(){
var bgNumber = getRandomInt(0, backgrounds.length-1);
}
3) update the H4 & body CSS to reflect the choice
$('body').css('background-image', 'url('+backgrounds[bgNumber].image+')');
$('h4').html(backgrounds[bgNumber].subtitle);
This will pick a new image & subtitle on each page load
The following is in JQuery:
Just name each of your images bg1 or bg2
// On Page Load
backgroundSelect();
function backgroundSelect(){
var sub1 = "this is my subtitle"
var numImgs = 5; // The Number of images you have total.
var select = Math.round(Math.random() * numImgs) + 1; // add one so not zero based.
$('body').css('background-image', 'bg' + select);
$('subtitle_element').replaceWith(sub1);
}
This is not the cleanest and most semantic way to write your code. But hopefully it will get you started in the right direction.
The simplest way, in plain JavaScript:
var images = [
{
subtitle : 'Subtitle text for image one...',
src : 'http://placekitten.com/1000/1000'
},
{
subtitle : 'Subtitle text for image two...',
src : 'http://lorempixel.com/1000/1000/people/'
},
{
subtitle : 'Subtitle text for image three...',
src : 'http://lorempixel.com/1000/1000/nightlife/'
},
{
subtitle : 'Subtitle text for image four...',
src : 'http://lorempixel.com/1000/1000/nature/'
}
];
function setBackground (images) {
// generates a random integer between 0 and the length of the supplied array:
var n = Math.floor(Math.random() * images.length),
// works out whether to use the 'textContent' or 'innerText' property:
textProperty = 'textContent' in document ? 'textContent' : 'innerText';
// sets the background-image of the 'body' element:
document.body.style.backgroundImage = 'url(' + images[n].src + ')';
// sets the text of the relevant subtitle element:
document.getElementById('subtitleElementID')[textProperty] = images[n].subtitle;
}
setBackground(images);
JS Fiddle demo.
Or, if you'd rather change the background every n milliseconds, you could add the following:
window.setInterval(function(){
setBackground(images)
}, 5000);
JS Fiddle demo.
Which, obviously, will change the image (and subtitle) every 5000 milliseconds.

Countdown Timer with Progress bar

Here is what i have so far: http://jsfiddle.net/BgEtE/
I am trying to get something like this: http://fusionmedia.dk/construction/
I need a progress bar like that and i need the days to be displayed like they have it. Also, i need to use a font called "Russel square" for the timer. I have looked all over but am having trouble.
for the timer you can use this one and you could integrate a progress bar, but I am not very sure.
This is another great tutorial that you could easily adapt to get what you want.
Well, I am not an expert but it's not so difficult, Take a look to this updated demo. Pay attention to the default variables // def values
var iCms = 1000;
var iMms = 60 * iCms;
var iHms = 3600 * iCms;
var iDms = 24 * 3600 * iCms;
this what you need to use to "schedule" the progress bar in this section:
// def options
var aDefOpts = {
start: new Date(), // now
finish: new Date().setTime(new Date().getTime() + 5 * iMms), // now + 5 days
For Example, if you write ...+5 * iMms it would be five minutes from now. iDms => Days / iHms=> hours / iCms=> seconds.
Also look at the css I've added in the demo, I think that to use a custom font, you first have to upload the font to your server, and then add the font in the style-sheet using something like this:
#font-face{
font-family: myFont;
src: url('myFont.ttf');
}
#font-face{
font-family: myFontEI;
src: url('myFont.eot');
}
Then Attach it as a font family like so...
font-family: myFont, myFontEI;

Categories

Resources