I need some sort of script to display diffrent content depending on the day of the week, mainly images. This is what I've tried
<script>
function myFunction() {
var d = new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="img src="http://totalscript.ro/logo.png";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
var x = document.getElementById("demo");
x.innerHTML=weekday[d.getDay()];
}
</script>
I want to make this able to display images. Can you help?
You can do the following:
var images = [
'http://my.site.com/img1.jpg',
'http://my.site.com/img2.jpg',
'http://my.site.com/img3.jpg',
'http://my.site.com/img4.jpg',
'http://my.site.com/img5.jpg',
'http://my.site.com/img6.jpg',
'http://my.site.com/img7.jpg',
];
function placeImage(id, images) {
document.getElementById(id).innerHTML = [
'<img src="',
images[(new Date()).getDay()],
'"/>'
].join('');
}
placeImage('demo', images);
Some Enhancements
Placing array of image sources outside the function will prevent recreation of array each time function is called
Using function parameters make it more generic and allow to populate for example another image container or take images from another source
[...].join('') is kind of string buffer that for old browsers may provide better performance
Not sure if you are just looking at how to assign an image to an item in JQuery? If that is it
$("#demo").attr("src","http://imageLocation");
or if you want to use your already created variable, which is using raw javascript:
x.attr("src","http://imageLocation");
Related
I have a gallery page that is updated often with new images. I use simple HTML to post the photos. My process currently is copy and paste the set of tags for a photo and change the number to correspond with the image file name. E.G. I change the number 047 to 048. Copy-Paste, change it to 049. This goes on until I have reached the number of additional photos. As you can see, this is very inefficient and there must be a better way of doing this. I was wondering if there is a simpler way to achieve this with Javascript? Perhaps generate additional tags by inputing a certain number or range?
Any ideas that would make this process efficient are welcomed please! Thank you!
<div class="cbp-item trim">
<a href="../assets/images/trim/img-trim-047.jpg" class="cbp-caption cbp-lightbox" data-title="">
<div class="cbp-caption-defaultWrap">
<img src="../assets/images/trim/img-trim-047.jpg" alt="">
</div>
</a>
</div>
You could use a templating solution. There are several libraries for that, but you can also implement it yourself.
Here is one way to do that:
Put the HTML for one image in a script tag that has a non-standard language property so the browser will just ignore it
Put some keywords in there that you'll want to replace, e.g. {url}. You can invent your own syntax.
Read that template into a variable
In the JS code, put all the images' URLs in an array of strings
For each element in that array, replace the keywords in the template string with that particular URL, and concatenate all these resulting HTML snippets.
Inject the resulting HTML into the appropriate place in the document.
Here is a snippet doing that:
// Add new images here:
var images = [
"https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/330px-SNice.svg.png",
"https://nettemarie357.files.wordpress.com/2014/09/smiley-face.jpg?w=74&h=74",
];
// Load the template HTML
var template = document.querySelector('script[language="text/template"]').innerHTML;
// Use template to insert all the images:
container.innerHTML = images.map(url => template.replace(/{url}/g, url)).join('');
img { max-width: 50px }
<div id="container"></div>
<script language="text/template">
<div class="cbp-item trim">
<a href="{url}" class="cbp-caption cbp-lightbox" data-title="">
<div class="cbp-caption-defaultWrap">
<img src="{url}" alt="">
</div>
</a>
</div>
</script>
This would help you creating it programatically:
var new_row = document.createElement('div');
new_row.className = "cbp-item trim";
var a = document.createElement('a');
a.href = "../assets/images/trim/img-trim-047.jpg";
a.className= "cbp-caption cbp-lightbox";
document.body.appendChild(a);
var div = document.createElement('div');
div.className = "cbp-caption-defaultWrap";
var img = document.createElement('img');
img.src= "../assets/images/trim/img-trim-047.jpg";
div.appendChild(img);
a.appendChild(div);
new_row.appendChild(a);
If it is just about printing HTML, I suggest you to use plugins like Emmet for Sublime Text editor.
When you install this plugin and see how it works, you can simple create a complex html in a way that 'for' loop would do this. This will help you to change only the image/link number of every item.
Check the demo in the link, that I added.
Here's an example in Java Script that will generate the html you will need. Set the total to whatever number you need to generate the number of images you want.
var total = 47;
var hook = document.getElementById('hook');
// Main Node for SlideShow
var node = document.createElement('div');
node.classList = "cbp-item trim";
// Work out the correct number
var n = function(int) {
var length = int.toString().length;
return length === 1
? '00' + int
: length === 2
? '0' + int
: length
}
// Create the item
var createItem = function(int){
// Create Anchor
var a = document.createElement('a');
a.href = '../assets/images/trim/img-trim-' + ( n(int) ) + '.jpg" class="cbp-caption cbp-lightbox';
a.classList = 'cbp-caption cbp-lightbox';
// Create Div
var div = document.createElement('div');
div.classList = 'cbp-caption-defaultWrap';
// Create Image
var img = document.createElement('img');
img.src = '../assets/images/trim/img-trim-' + ( n(int) ) + '.jpg';
img.alt = 'gallery image';
// Finalise Dom Node
var container = div.appendChild(img)
a.appendChild(div);
// Return Final Item
return a
}
// Create Items
for (var i = 1; i < total + 1; i++) {
node.appendChild(createItem(i));
}
// Append Main Node to Hook
hook.appendChild(node);
<div id="hook"></div>
I have wrote this javascript to show some images with id: imgFotogramma1/imgFotogramma2/ecc.. randomly in 8 different div with id Fotogramma1/Fotogramma2/ecc..:
function rullino() {
var immagini = new Array("strutture/1.jpg", "strutture/2.jpg", "strutture/3.jpg", "strutture/4.jpg", "strutture/5.jpg", "strutture/6.jpg", "strutture/7.jpg", "strutture/8.jpg", "strutture/9.jpg");
for (i = 1; i < 9; i++) {
var x = Math.floor(immagini.length * Math.random(1));
var imgId = "imgFotogramma" + i;
$(function () {
$(imgId).fadeIn(1000);
src = $(imgId).attr('src');
src = immagini[x];
alert(src);
});
}
setInterval("rullino()", 4000);
};
Now,this code start when body is loaded and its repeated every 4 seconds but i don't understand why the images are not displayed. I have started to work with Jquery not too much time ago and probably something are wrong.
I want to specify that: if i use normally javascript to assign to the src attribute the value of immagini[x],all work fine and the images are displayed.I have problem only to apply the fadein() motion.
I need a help to understand where is wrong,i have studied the fadeIn() API and i have tried to apply to my case.
Thanks in advance to anyone want to help me.
$(imgId).fadeIn(1000);
should be:
$('#'+imgId).fadeIn(1000);
Use # + idOfElemnt to select element with particular id.
You already doing it right. Just replace
var imgId = "imgFotogramma"+i;
With
var imgId = "#imgFotogramma"+i;
Since your are using the ID of the image, then your must have to use the "#" for id for applying the jQuery on it.
To select an ID, use # + elemID. Like this:
var imgId = "#imgFotogramma" + i;
Also, fade will not occur if the element is not hidden. First hide it, and then fade it in:
$(imgId).hide().fadeIn(1000);
I have a background image folder that there is some picture that i want to use them for background.
how i can get their names and put them on array whit javascript?if i cant they do with javascript,how can i do that?
i want to read name of files and use javacsript and link for change background image whit css.
<script>
function nextbg(){
$('#bg').css('background-image','url(Images/bg2.jpg)');
}
</script>
This solution is created according to the fact that browser dont have access to folders/filesystem.
Javascript can not access the filesystem. This has to be done by a server script and then be feed to the javascript.
I had the simliar problem when building my game engine when I was loading all my diffrent tiles. I ended up doing it like this.
This solution do pose two a problems when implementing it.
You will have to define the amout of images in the "NrofTiles" array
The images must be named like tile1, tile2 ... tile9 so you can
increment the path to them.
The typeOfTiles[typeCounter] is just there to give me access to different folders, in my case for my tiles, grass, houses, water and so on.
for(var i = 0; i <= nrofTiles.length; i++)
{
for(var x = 0; x <= nrofTiles[i]; x++)
{
console.log
("Fetching tile "+(x + 1 )+" of " + 14);
img = new Image();
//My path
img.src = 'Images/Cart/' + typeOfTiles[typeCounter] + '/' + (x + 1) + '.png';
imgArray.push(img);
var intervalFunctionen = function () {
alert("calls back here");
};
}//end for loop!
}end outer for loop!
When everything is loaded(the tiles), you do this to change the background picture.
This is an example of a changing body background. You could make a link with an ID lets say "iamthelink".
HTML
Change BG
JAVASCRIPT
var link = document.getElementsById('iamthelink');
link.onclick= function() {
var body = document.getElementsByTagName('body')[0];
body.style.backgroundImage = 'url(http://localhost/background.png)';
}
I've the following code which will take an array and append to the page dynamically a QR code with the text being an element in the array.
$(document).ready(function () {
var list = ['dog', 'cat', 'mouse', 'hippo', 'ox'];
var qrUrl = 'https://chart.googleapis.com/chart?';
//functions
function getQrCodes(array) {
$.each(array, function (ix, val) {
//options gets chl property redefined for each element
//in the array
var options = {
cht: 'qr',
chs: '300x300',
chl: array[ix]
}
qrOptionArray.push(options);
console.log('this qr should be: ' + array[ix]);
console.log(qrUrl + $.param(options));
var $img = $('img').attr('src', qrUrl + $.param(options)).appendTo('body');
});
}
getQrCodes(list);
});
You can see the console output from the fiddle here although for some reason the QR codes don't appear in the fiddle window, they do on my local machine. The problem I've got is that the last regardless of the fact that you can see the console output change for each element in the array, the only QR code I get is the last element in the array repeated X number of times. Each of those QR cans will scan and print 'ox', even though the console output is correct. What's going on here?
The selector where you append the image to the body is wrong. You are selecting all existing img elements, whereas you want to create a new one. Try this:
var $img = $('<img />').attr('src', qrUrl + $.param(options)).appendTo('body');
Example fiddle
Note: $('<img />') not $('img').
Pretty much as the title. I have been asked if it is possible to have a specific banner shown in a section on a website on different days without any external user input.
My first thoughts are the use of javascript/jquery. We are limited with the functionality however as the site is controlled by the horror that is Netsuite.
Any help/ideas are appreciated :)
-Wayne
EDIT: With regard to your comment, it sounds like you want to load a different slideshow depending on the day of the week.
Here's a simple generic example of how it could be done.
// Insert the code that loads the individual slideshows in the functions below
var slideshows = [
function() { /* insert code to load some slideshow */ },
function() { /* insert code to load some other slideshow */ },
function() { /* insert code to load a different slideshow */ },
function() { /* insert code to load yet another slideshow */ }
];
// call a slideshow function depending on the day of week
slideshows[ new Date().getDate() % slideshows.length ]();
This will call a different function from the Array depending on the day of week. You don't need seven of them. It will automatically rotate.
There are other ways to approach this, but I'd need to see how the slideshows are set up. This is a simple approach.
If you have more than 7 different slideshows, it will need to be changed a bit.
EDIT: This answer assumes you meant different per day of week. Not sure if that was your intention.
This is probably better than my original answer since it doesn't require loading all the banners.
javascript only version
Example: http://jsfiddle.net/patrick_dw/5drgu/4/
var banners = [
"http://dummyimage.com/120x90/f00/fff.png&text=my+image",
"http://dummyimage.com/120x90/0f0/fff.png&text=my+image",
"http://dummyimage.com/120x90/00f/fff.png&text=my+image",
"http://dummyimage.com/120x90/ff0/fff.png&text=my+image"
];
var banner = new Image();
banner.src = banners[ new Date().getDate() % banners.length ];
document.getElementById('container').appendChild( banner );
jQuery version
Example: http://jsfiddle.net/patrick_dw/5drgu/7/
(changed it a bit so it doesn't start with an empty <img>)
var banners = [
"http://dummyimage.com/120x90/f00/fff.png&text=my+image",
"http://dummyimage.com/120x90/0f0/fff.png&text=my+image",
"http://dummyimage.com/120x90/00f/fff.png&text=my+image",
"http://dummyimage.com/120x90/ff0/fff.png&text=my+image"
];
var banner = $('<img>', { src:banners[ new Date().getDate() % banners.length ]})
.appendTo('#container');
html
<div id='container'></div>
Original answer:
Here's one way:
Example: http://jsfiddle.net/patrick_dw/5drgu/
var banners = $('#container img').hide();
banners.eq( new Date().getDate() % banners.length ).show();
html
<div id='container'>
<img src = "http://dummyimage.com/120x90/f00/fff.png&text=my+image" />
<img src = "http://dummyimage.com/120x90/0f0/fff.png&text=my+image" />
<img src = "http://dummyimage.com/120x90/00f/fff.png&text=my+image" />
<img src = "http://dummyimage.com/120x90/ff0/fff.png&text=my+image" />
</div>
The first thought should be server-side.
If that is not an option then you could do it with javascript/jquery with the limitations it brings. Javascript enabled browsers.
You could name your files accordingly ie. image-19-7-2011.jpg and use the Date() object to create the filename to use for the current date.
Something like
var d = new Date();
var filename = 'image-' + d.getDate() + '-' + d.getMonth() + '-' + d.getFullYear() + '.jpg';
document.getElementById('banner').src = '/path/to/' + filename;
example at http://jsfiddle.net/rZaqx/
var now = new Date();
var date = now.getMonth() + "-" + now.getDay();
switch(date) {
case "04-01":
$('<p>APRIL FOOLS!</p>').appendTo("body");
break;
case "01-01":
$('<p>Happy New Year!</p>').appendTo("body");
break;
}
This answer assumes you want a different banner image for each day of the week.
If you aren't able to update the banner in the backend then it would be possible just to have all the banners on the page, hidden with the CSS display: none.
Then just use something like:
var date = new Date();
$("#banner" + date.getDay()).show();
This will work if you have 7 elements named banner0 for Sunday, banner1 for Monday, etc.
Alternatively, if you just want to change the banner image then you could set your CSS like so:
div#banner { background-image: url(default.jpg)} // Common styling
div#banner.day0 { background-image: url(image0.jpg); } // Image for Sunday
div#banner.day1 { background-image: url(image1.jpg); } // Image for Monday
div#banner.day2 { background-image: url(image2.jpg); } // Image for Tuesday
Then your jQuery could look like:
var date = new Date();
$("div#banner").addClass("day" + date.getDay());
Of course, the issue with both these options are that you need to have a different banner for each day. They're just some ways you can do it (but definitely not the only ways)