im trying to write a script to change my body background based on the whether its am or pm, I have the following, only its not working, can anybody see why?
<!-- Change background -->
var currentTime = new Date().getHours();
if (7 <= currentTime && currentTime < 20) {
if (document.body) {
document.body.background = "images/backgrounds/day.jpg";
}
}
else {
if (document.body) {
document.body.background = "images/backgrounds/night.jpg";
}
}
<!-- Change background -->
A good idea would be to actually use jQuery selectors and modify the CSS:
$('body').css({
background: 'url(yourUrl)'
});
there maybe several problems with this
1) I can't seem to access those two images. Are they actually at the path you specified?
http://int.test.venndigital.co.uk/correlatesearch/_includes/images/backgrounds/day.jpg
http://int.test.venndigital.co.uk/correlatesearch/_includes/images/backgrounds/night.jpg
This should be what you need. You should really try to learn javascript instead of just asking people to write it for you, though. Either that or hire someone else to do the job.
$('body').css('background-image', function(){
var url, hour = new Date().getHours();
if (hour > 7 && hour < 20) {
return 'http://example.com/day.jpg';
} else {
return 'http://example.com/night.jpg';
}
});
Related
I'm working on building a page to be a simple to look at page that tells the user if a shop is open or closed. I'm trying to have it display a green background and "yes, open" or a red background with "no, closed". The schedule varies every day of the week and some days the shop closes midday and reopens later. I'm having trouble getting the background and text to correctly change according to the time.
I tried implementing solutions from this user's similar problem, but I couldn't quite get them to work. I tried both the solution from 'Arnav Aggarwal' as well as the one below it from 'Darkisa'. Arnav's uses a flag set false and if statements.
When using the flag it seems to not care about the hours, only the day, put perhaps I am simply doing it wrong. Below is a code snippet, but I also have the code set up on codepen.io
let t = document.getElementById("Status");
t.innerHTML = "No";
document.body.style.backgroundColor = "red";
var q = new Date();
var hour = q.getHours();
var day = q.getDay();
function isBetween(testNumber, lowerLimit, upperLimit) {
return testNumber >= lowerLimit || testNumber <= upperLimit;
}
var flag = false;
if (day === 2 && (isBetween(hour, 0, 5) || isBetween(hour, 6, 7))) {
flag = true;
}
if (flag) {
let t = document.getElementById("Status");
t.innerHTML = "Yes";
document.body.style.backgroundColor = "green";
}
#status {width: 3em}
<div id="Status"></div>
For me, Arnav's code seems more my speed as it is clearer what is happening and I'm not super familiar with loops and arrays like Darkisa's reply.
I additionally tried making a series of if else statements, but they do not work unless the day is [6], or Saturday.
Code using Arnav's Flag solution
Code using stacked If Else
Update: I found a better way of doing this. There's a library called Backstretch.
I hope it will be helpful for someone else.
I'm trying to change the background of the tag every 10 seconds with animation but after a while of working, it does change every 2-3 seconds instead of 10.
What is wrong with the code? Why does it go crazy after a while of waiting as I explained above? For example, after about 10 minutes or so.
<section class='set-bg'>...</section>
$('.set-bg').each(function() {
var bgs = [];
$.get('/api/listbanners', (e) => {
bgs = e["background"];
x(0);
});
function x(i) {
$('.set-bg').css('background-image', 'url(' + bgs[i] + ')').fadeTo(0, 0.6).fadeTo(1000, 1);
i++;
if (i == bgs.length) {
i = 0;
}
setTimeout(x, 10000, i);
}
});
I'm currently learning JS and i'm working on my own first library, however a problem i stumbled upon is:
When someone else uses my library he/she will get a name conflict while using 'alerts' in there code.
What is the best methode or how can i best solve this issue?
Thanks in advance!!
body {
font-family: sans-serif;
background: white;
font-size: 150px;
color: #333;
}
jQuery(document).ready(function( $ ){
function alerts (alert1, alert2, alert3, alert4) { //function calling all alerts
var hours = new Date().getHours(); //get time by hours
if (alert1 == undefined) { // if statement that fills the alert if undefined
alert1=0;
}
if (alert2 == undefined) {
alert2=12;
}
if (alert3 == undefined) {
alert3=17;
}
if (alert4 == undefined) {
alert4=24;
}
if (hours >= alert1 && hours < alert2) { //check if the time is between alert1 and alert 2, if than so execute
document.body.style.backgroundColor = "blue";
} else if (hours >= alert2 && hours < alert3) {
document.body.style.backgroundColor = "red";
} else if (hours >= alert3 && hours < alert4) {
document.body.style.backgroundColor = "green";
} else {
}
}
alerts(a, b, c, d);
}); //end Jquery
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>timeofday</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> <!-- Includes Jquery -->
<script>
var a = 0;
var b = 17;
var c = 18;
var d = 24;
</script>
<script src="js/index.js">
</script> <!-- Includes the script for background change -->
</body>
</html>
You can encapsulate / namespace your JS in various ways. I personally like this scheme:
var myns = {
send: function () {
// your code
},
receive: function (sender) {
// your code
},
save: function () {
// your code
}
};
it has no limitations as far as i know and you can use nice short names :-) simply call for example this from outside:
myns.receive(this);
You should rename alerts(...) to something else. Try to name it so that when another programmer reads it, he/she directly knows by just the name of the function, what the function will probably do (of course this isn't always fully possible, but try to). The current name isn't really describing what it does, and aside from that also giving you conflicts. Something you could do is naming it adjustBackgroundColorAccordingToTime or setBackgroundForCurrentTime. Something else may work for you too of course :)
Do not name your library that normal, and make the name longer.
Then, you can explode a function such as noConflict to explode your lib just like jQuery.noConflict does.
For example:
The full name of your lib is MyAwesomeAlerts, and you would like to make a short name alerts.
The end of your code, you should detect whether your short name exists in current scope, execute statement window.alerts = MyAwesomeAlerts if not exists; otherwise, do nothing, and the end users can invoke var awesomeAlerts = MyAwesomeAlerts.noConflict(); to name it.
In function noConflict, just like this:
```
MyAwesomeAlerts.noConflict = function() {
return MyAwesomeAlerts
}
```
$(document).ready(function fadeIt() {
$("#cool_content > div").hide();
var sizeLoop = $("#cool_content > div").length;
var startLoop = 0;
$("#cool_content > div").first().eq(startLoop).fadeIn(500);
setInterval(function () {
$("#cool_content > div").eq(startLoop).fadeOut(1000);
if (startLoop == sizeLoop) {
startLoop = 0
} else {
startLoop++;
}
$("#cool_content > div").eq(startLoop).fadeIn(1500);
}, 2000);
});
Here I want a class of divs to animate, infinitely!
However, because the interval is set to two seconds there is period where no div is showing!
What would be an appropriate way to loop the animation of these divs?
I thought about using a for loop but couldn't figure out how to pass a class of divs as arguments. All your help is appreciated.
Thanks!
Ok, generally, you should know that Javascript is a single threaded environment. Along with this, the timer events are generally not on time accurately. I'm not sure how jQuery is doing fadeIn and fadeOut, but if it's not using CSS3 transitions, it's going to be using timeOut and Intervals. So basically, there's a lot of timer's going on.
If you go with the for loop on this one, you'd be blocking the single thread, so that's not the way to go forward. You'd have to do the fade in/out by yourself in the setInterval.
Setting the opacity on each interval call. Like div.css('opacity', (opacity -= 10) + '%')
If you're trying to fade in and out sequentially, I think maybe this code would help
var opacity = 100,
isFadingIn = false;
window.setInterval(function() {
if (isFadingIn) {
opacity += 10;
if (opacity === 100) isFadingIn = false;
} else {
opacity -= 10;
if (opacity === 0) isFadingIn = true;
}
$('#coolContent > div').css('opacity', opacity + '%');
}, 2000);
Consider the following JavaScript / jQuery:
$(function(){
var divs = $('#cool_content > div').hide();
var curDiv;
var counter = 0;
var doUpdate = function(){
// Hide any old div
if (curDiv)
curDiv.fadeOut(1000);
// Show the new div
curDiv = divs.eq(counter);
curDiv.fadeIn(1000);
// Increment the counter
counter = ++counter % divs.length;
};
doUpdate();
setInterval(doUpdate, 2000);
});
This loops infinitely through the divs. It's also more efficient than your code because it only queries the DOM for the list of divs once.
Update: Forked fiddle
instead of
if (startLoop == sizeLoop)
{
startLoop = 0
}
else
{
startLoop++;
}
use
startLoop =(startLoop+1)%sizeLoop;
Check the demo http://jsfiddle.net/JvdU9/ - 1st div is being animated just immediately after 4th disappears.
UPD:
Not sure I've undestood your question, but I'll try to answer :)
It doesn't matter how many divs you are being looped - 4, 5 or 10, since number of frames are being calculated automatically
x=(x+1)%n means that x will never be greater than n-1: x>=0 and x<n.
x=(x+1)%n is just shorten equivalent for
if(x<n-1)
x++;
else
x=0;
as for me first variant is much readable:)
And sorry, I gave you last time wrong demo. Correct one - http://jsfiddle.net/JvdU9/2/
JS beginner here;
Ok, I'm trying to manipulate the functions of Codaslider for a layout. What I need is the ability to use an image for slide dynamic slide navigation.
I've solved the issue for dynamic hashing, however I'm stuck at modifying the HTML. I've tried a few things but I figure this is the easiest way...
This is what I've got so far;
function navigate ()
{
var url = document.getElementById('back');
url.href = page_back();
return url;
}
function page_back(inward)
{
new Object(inward.location.hash);
var rehash = inward.location.hash.match(/[^#]/);
if (rehash == 1) {
rehash = 5;
}
else if(rehash == 2) {
rehash = 1;
}
else if(rehash == 3) {
rehash = 2;
}
else if(rehash == 4) {
rehash = 3;
}
else if(rehash == 5) {
rehash = 4;
}
else if(rehash == null) {
rehash = 5;
}
else{rehash = "Invalid URL or REFERRER"}
inward.location.hash = rehash;
return inward.location.href;
};
Implemented here;
<a href="#5" id="back" class="cross-link"> <input type="image" class="left_arrow" src=
"images/leftarrow.png" onclick="navigate()" /></a>
What I expect this to do is change the href value to "#1" so that Codaslider will do it's thing while I provide a stationary dynamic image for slide browsing.
Anyone have any idea what i'm doing wrong? page_back works fine but navigate seems to be useless.
sup Josh
so to start this line here
new Object(inward.location.hash);
Unless i completely missed some javascript weirdness that line should not do any thing
the function
function page_back(inward)
takes a inward argument but you call it from navigate without an argument
url.href = page_back();
ps. the location object can be found on window.location
happy coding :D