Different backgrounds for different time of day? [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Changing background based on time of day (using javascript)
I'm looking to create a site where the background rotates a bunch on files for different times of day. Is there any way I can tie maybe a bit of javascript to change the background at certain times based on the either the server or script clock?
I'm looking to have a day/afternoon/evening/night/dawn set of backgrounds that I want to cycle through.

Using the code in this question, fetch the local time, and change the CSS of the element, which keeps the background.

You could do something like this, and then just pass the i variable to the element background-image:
var d = new Date(),
h = d.getHours(),
i;
if (h < 6) i = "night.jpg";
else if (h < 9) i = "dawn.jpg";
else if (h < 15) i = "afternoon.jpg";
else if (h < 21) i = "day.jpg";
else i = "night.jpg";
document.body.style.background = "url("+i+")";
http://jsfiddle.net/niklasvh/UZG9z/

Add this into the head of your HTML document:
<script type="text/javascript">
(function(){
var styles = ['night', 'dawn', 'afternoon', 'day', 'evening'];
var currStyle = styles[Math.floor(styles.length * (new Date()).getHours() / 24)];
document.documentElement.className += ' ' + currStyle;
}());
</script>
Then in your CSS you can use something like this:
.night #myelement {
background-image: url(myImage.jpg);
}
.day body {
background-color: red;
}

Related

Isolating a part of a string

well... for begining, i m building some dumb and easy projects because i'm starting learning the world of front end development. One of those you can find in internet was this Color picker idea. Some page where with a button you can generate a random color. all random, no connections between the colors o something else.
(i'm not a native english speaker so sorry if i write something and you dont get it right)
Here's the link to the repository
so...
I build a function that makes a random HSL color randomizing the values and then building a string and puting that in the css
function getRandomHsl(){
let hueValue = 0;
hueValue = Math.floor(
Math.random() * (360 + 1)
)
let satValue = 0;
satValue = Math.floor(
Math.random() * (100 + 1)
)
let lightValue = 0;
lightValue = Math.floor(
Math.random() * (100 + 1)
)
return 'hsl(' + hueValue + ', ' + satValue + '%, ' + lightValue + '%)';}
if you can give me your opinion on that function and tell me if you would have done it inanother way.
so... i wanted to find the way to if the Lightness would have a low value the color of the font change it to some white or something like that. And this is what i figured out. (the first part of the code is the button changing the value of the background color of the main div. This works well. The problem comes after).
hslBtn.addEventListener('click', () => {
let hslStringComplete = getRandomHsl();
colorShowcase.textContent = hslStringComplete;
document.getElementById('color-container').style.backgroundColor = hslStringComplete;
/*================================= change the color font od the text when its to dark */
let hslLightValue = hslStringComplete;
let lightValue = hslLightValue.toString().substr(13,3).replace(/\D/g,'')
console.log(hslLightValue.substr(13,3).replace(/\D/g,''));
if(lightValue < 40){
innerHTML('input').style.color = "white";
}})
i have really strougle it out coming up with this idea so i want some opinion on how could i have done in other way.
PD: `if(lightValue < 40){
innerHTML('input').style.color = "white";}
this is hte HTML: <input class="background-container"><h3 class="forWhiteColor">Background Color : <span class="color-showcase">#messi</span></h3></input>
this part get me an error and the html doesn get changes. Here's the error.
console error
thanks in advance.
innerHTML('input') should probably be document.getElementById('color-container') instead.
also you should note that when you extract a part of a string, you get a string.
And comparing a string to a number won't work well, you first need to convert your string to a number with parseInt (for integers) or parseFloat (for float)

Function is not defined? [duplicate]

This question already has answers here:
Why does firebug say my function call is "undefined"
(2 answers)
Pass parameters in setInterval function
(19 answers)
Closed 8 years ago.
I have this code: (Stripped pieces not related to question)
$(function() {
mins = 0; //Set the number of minutes you need
//secs = 0;
function Decrement(mins){
var secs = mins * 60;
var currentSeconds = 0;
var currentMinutes = 0;
if(currentSeconds <= 9){ currentSeconds = "0" + currentSeconds; }
secs--;
document.getElementById("commercial").innerHTML = "Please wait "+currentMinutes + ":" + currentSeconds; //Set the element id you need the time put into.
if(secs !== -1){ alert("Done!"); }
}
function runCommercial(time){
$('#commercial').html('Plase wait 8:00');
$('#commercial').attr("disabled", "disabled");
mins = 8;
setInterval('Decrement(8)',1000);
}
$('#commercial').click(function(){
runCommercial(30);
});
});
Whenever I click the commercial button, the button text gets set to 8:00 as it should, altough it won't count down, instead it gives me "Decrement() is not defined" in the dev console of firefox. Why is this happening and how do I fix it?
Thanks.
This is happening because the String 'Decrement(8)' is being evaluated in the global namespace, not under your IIFE closure.
Change
setInterval('Decrement(8)',1000);
To
setInterval(function () {Decrement(8);}, 1000);
It's considered bad practice to cause an eval-style interpretation of code, try to always pass functions into setTimeout and setInterval, etc.

How to open an element as popup only to a certain precentage of the users

I have a js which is integrated into other websites. When the user enters the site, a function is called from the script and an element pops up.
Is it possible for me, in the js function that pops-up the element, to make it open only for a certain percentage (let's say 60%) of the users?
I thought about using the Math.random() function, but i'm not sure how to make it.
EDIT:
After thinking about it, it might be that this is not achievable by javascript alone and it will require the use of some kind of tracking of users (via database or such). If someone knows of a different way, I'll be happy to hear it.
It is easily achievable by Javascript, and it's very simple!
var pctg = 60; // Set percentage here
var rndm = Math.ceil(Math.Random() * 100);
if (rndm <= pctg) {
// Execute popup statement(s)
}
On a first glance, this code snippet gives a 60% chance that the popup will occur: that is, one page view is completely independent from another page view. It can easily happen that 20 or more subsequent visitors get the popup, but the opposite is also possible. But the more visitors, the closer the 60% will be approached.
If you want to be mercillesly accurate, you can say 'set the percentage that a given visitor will receive the popup'.
This method will not attempt any kind of balance, it relies purely on sheer number of page views. Also, do not forget, that this is per page view.
If you want to remember whether or not a certain user should receive popups between visits, you can use cookies:
document.cookie="bShowPopup=0"; or document.cookie="bShowPopup=1";
This also opens up the possibility to create a more powerful code, one that creates a given chance of displaying the popup per page view, up until the point that the popup has already been displayed once:
First a function to read and write the specified cookie string:
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
}
return "";
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
Please check out http://www.w3schools.com/js/js_cookies.asp for more information regarding the use of cookies.
Next we could do this:
// See if the user already received the popup
// The if statement will only evaluate to true if the popup is *not* explicitly disabled (that is, it is set to 1, or not set)
if (getCookie('bShowPopup') !== '0')
{
var pctg = 60; // Set percentage here
var rndm = Math.ceil(Math.Random() * 100);
if (rndm <= pctg) {
// Execute popup statement(s)
//stmt123....
// Set cookie bShowPopup to 0 (so the user won't receive popups ever again)
// NOTE: The cookie will expire after 30 days.
setCookie('bShowPopup', '0', 30);
}
}
Another approach, that will create the closest result without any server-side programming or user-tracking is to check whether a certain user should be shown popups only once, and then store the decision result in a cookie. The only thing to modify in the previous code is to set the bShowPopup cookie to 0 even if the popup wasn't shown.
if (getCookie('bShowPopup') !== '0')
{
var pctg = 60; // Set percentage here
var rndm = Math.ceil(Math.Random() * 100);
if (rndm <= pctg) {
// Execute popup statement(s)
//stmt123....
}
setCookie('bShowPopup', '0', 30);
}
Please, also refer to http://www.w3schools.com/jsref/jsref_random.asp regarding the use and return valies of Math.random().
Using Math.Random() is a good choice for this. Math.Random() generates a number between 0 and 1, so if you want a random number between 0 and 10, multiply the result by 10, then take the ceiling of that number to remove the decimal places and convert it to a round number. For 0 to 100, multiply it by 100. At the beginning of your pop-up function, add the following:
var rand = Math.Random() * 100;
next wrap the code that displays the popup in an if statement that checks to see if the random number you generated is less than or equal to 60:
if(Math.ceil(rand) <= 60) {
...
}
Heres an example of what I did when I needed this functionality
The following code would be a bit easier to maintain if you change the number of options or the chance percentage.
var contentId, random = Math.random();
if (random < 0.5) {
// option 1: chance 0.0–0.499...
contentId = 0;
} else (random < 0.75) {
// option 2: chance 0.50—0.7499...
contentId = 1;
} else {
// option 3: chance 0.75–0.99...
contentId = 2;
}
loadContent(contentId);
EDIT Based on comment feedback.
Glad to help. If this is a php page then you don't need ajax. Simply update/return the count at the top of the page via php/sql and then echo that figure into your JS function. You only need to check whether the figure is divisible by 3. If it is then run your popup function. This way you can also report on the amount of times the popup would have been activated.

javascript timer not working

I have a little javascript which I'm trying to use to make a timer. I got the code from another question on this site and it works ok on it's own, but since I'm making a few timers on this page I need to modify it a little and my modifications break it.
I'm not so brilliant with javascript and I can't see where I'm going wrong. All I've really done is add numerals (the id's of the products which have the timers) to the variable and function names. I've read it's ok to have numerals in variable and function names, so I'm at a loss.
The code I'm using (which isn't working) is:
$(document).ready(function () {
var x1, secs1 = 61434; //declared globally
x1 = setInterval(myFunc1, 1000);
function myFunc1() {
alert('yo');
var minutes = Math.floor(secs1 / 60);
var seconds = secs1 % 60;
$('#timer_'1).html(minutes + ':' + seconds); //assuming there is a label with id 'timer'
secs1--;
if (secs1 == 0) {
document.getElementById('timer').style.hidden = true;
clearInterval(x1);
}
}
});
Your question is unclear, and it's not obvious to me what you're trying to do. But one obvious problem is in these two lines:
$('#timer_'
1).html(minutes + ':' + seconds); //assuming there is a label with id 'timer'
That will throw a syntax error, because '#timer_'1 is not valid syntax.
Two issues here with the css selectors:
$('#timer_'1).html(minutes + ':' + seconds); //add a + between timer_ and 1
document.getElementById('timer') //should be timer_1 too
fiddle http://jsfiddle.net/Drea/1zvLspxd/

Is it possible to determine the hex value of a named color? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript function to convert color names to hex codes
Is it possible to retrieve or calculate the hex value that the browser is currently using for a named color? For instance I would like to be able to do something like the following:
(Html):
<div id="container" style="background-color: lightgreen"></div>
(JavaScript):
var container = document.getElementById("container");
var colorAsHex = getHexColor(container, "background-color");
At best I'm hoping for a jQuery solution that I just happen to be missing. At worst I'm fine with browser-specific hacks as long as I can cover the 4 major browsers.
$('div').css('background-color') seems to be working ... see this example link
var namedColor = "lightgreen";
var rgbColor = $("<div></div>").css("background-color", namedColor).css("background-color");
var match = rgbColor.match(/(\d+),\s*(\d+),\s*(\d+)/);
var value =
(+match[1] << 16) +
(+match[2] << 8) +
(+match[3] << 0);
var hexColor = value.toString(16);
while (hexColor.length < 6) {
hexColor = "0" + hexColor;
}
console.log("#" + hexColor)
Demo here and here.

Categories

Resources