I am trying to write a function that will change between an array of images. What I have makes sense to me, but when I run it as it is below then the first image loads, then the second image loads at some point (the transparency doesn't change) and then nothing happens. Here is the javascript code:
var image1 = new Image();var image2 = new Image(); var image3 = new Image();
image1.src = "images/website6.jpg"; image2.src = "images/website7.jpg"; image3.src = "images/sunset.jpg";
var images = new Array("images/website6.jpg","images/website7.jpg","images/sunset.jpg");
/*document.slide.style.opacity = 1;
document.slide.stylebg.opacity = 0;*/
setTimeout(function() { fade(images,0); }, 2000);
function delay(arr,num)
{
document.slide.src = arr[num % 3];
document.slide.style.opacity = 1;
document.slidebg.style.opacity = 0;
document.slidebg.src = arr[(num+1)%3];
var number = num + 1;
setTimeout(function() { fade(arr,number); }, 2000);
}
function fade(arr,num)
{
/*alert('fadebefore ' + (document.slide.style.opacity).toString())*/
document.slide.style.opacity -= 0.1
/*alert('fade')*/
document.slide.stylebg.opacity += 0.1
if (document.slide.style.opacity == 0)
{
setTimeout(function() { delay(arr,num); }, 150);
}
else
{
setTimeout(function() { fade(arr,num); }, 1500);
}
}
The HTML is simple. I have two classes; style and stylebg. style sits in front of stylebg and then I change opacities and images as needed. The javascript seems logical to me, but it doesn't work as expected. Also worth noting is there are 3 comments. The first comment (line 3-4) is attemping to set the opacities to what they should be at the beginning. However, if I do this then I get even less progress than above: the first image loads and nothing else happens. The second two comments are used for debugging purposes. If I uncomment these then the image change occurs between the two alerts, which would seem to say the image change is caused by the opacity change.
So can anybody explain why it isn't doing what I expect it to? Thanks.
EDIT: Some more code:
HTML (This is the only part being affected):
<div style="position: relative;">
<img src="images/sunset.jpg" id="slide" />
<img src="images/website6.jpg" id="slidebg" />
</div>
CSS:
#slide{
display:block;
margin-left:5;
margin-right:auto;
border: 1px solid black;
z-index: 1;
top: 0px;
position: relative;
}
#slidebg{
display:block;
margin-left:auto;
margin-right:auto;
border: 1px solid black;
z-index: 0;
top: 0px;
position: absolute;
}
Answering for formatting's sake. I have not debugged to see what would work, but this makes more sense to me
If you want to use ID, use document.getElementById, if you want to use name, use document.images[imgname] or document.imagename
You are mixing names and style too. document.slide.stylebg.opacity and such
This does something. Not sure it is what you want: http://jsfiddle.net/EcShW/2/
<div style="position: relative;">
<img src="images/sunset.jpg" id="slide" name="slide" />
<img src="images/website6.jpg" id="slidebg" name="slidebg" />
</div>
var images = []; // can be more elegant, but this is simpler
images[0]=new Image(); images[0].src="images/website6.jpg";
images[1]=new Image(); images[1].src="images/website7.jpg";
images[2]=new Image(); images[2].src="images/sunset.jpg";
var tid1,tid2,tid3
tid1=setTimeout(function() { fade(images,0); }, 2000);
function delay(arr,num)
{
document.slide.src = arr[num % 3].src;
document.slide.style.opacity = 1;
document.slidebg.style.opacity = 0;
document.slidebg.src = arr[(num+1)%3].src;
var number = num + 1;
tid2=setTimeout(function() { fade(arr,number); }, 2000);
}
function fade(arr,num)
{
document.slide.style.opacity -= 0.1
document.stylebg.style.opacity += 0.1
if (document.slide.style.opacity == 0)
{
tid3=setTimeout(function() { delay(arr,num); }, 150);
}
else
{
tid3=setTimeout(function() { fade(arr,num); }, 1500);
}
}
You can't just refer to page elements by "id" value like that; you have to use "document.getElementById()":
var slideElement = document.getElementById('slide'), slidebgElement = document.getElementById('slidebg');
Then you'd work with "slideElement.style" etc. instead of "document.slide.style".
EDIT2
It works for me (chromium)
var images = new Array ();
images[0] = new Image();
images[0].src = "images/website6.jpg";
images[1] = new Image();
images[1].src = "images/website7.jpg";
images[2] = new Image();
images[2].src = "images/sunset.jpg";
function delay ( arr, num )
{
slide.src = arr[num % 3].src;
slide.style.opacity = 1;
slidebg.style.opacity = 0;
slidebg.src = arr[(num+1)%3].src;
var number = num + 1;
setTimeout(function() { fade(arr,number); }, 2000);
}
function fade(arr, num)
{
if ( slide.style.opacity == 0 )
setTimeout(function (){ delay(arr, num); }, 150);
else
{
slide.style.opacity = (slide.style.opacity*10 - 1)/10 ;
slidebg.style.opacity -= -0.1;
setTimeout ( function(){fade(arr,num);}, 1500 );
}
}
fade (images, 0);
AHA!
<img id="img_id"/> we can get by document.img_id, even in chromium
OK, OK, removed links to this WE TEACH YOU TO FAIL AT WEB DEV site..
Related
I would like to build an image gallery like this where pictures keep looping automatically but at the same time, it's possible to interact through the gallery using the mouse wheel as well. I would also achieve an effect like that where images, instead of scrolling out of the screen shrink on the side.
So I was trying to understand where to start and I couldn't find any library for the task so I tried from scratch using vanilla js, this is my attempt.
var testArray = document.querySelectorAll(".image");
var totImg = testArray.length;
var contIterazioni = 0;
var test = testArray[contIterazioni];
var bounding = test.getBoundingClientRect();
function LoopFunction() {
setInterval(galleryScroll, 20);
}
function galleryScroll() {
test = testArray[contIterazioni];
bounding = test.getBoundingClientRect();
if (bounding.left == 0) {
//console.log("immagine bordo sx");
if (test.width > 0) {
test.width = test.width - .25;
} else {
contIterazioni = contIterazioni + 1;
if (contIterazioni >= totImg){
contIterazioni = 0;
}
}
}
}
LoopFunction();
body{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
width: 100vw;
height: 100vh;
display: flex;
overflow: hidden;
}
<div class="container">
<img src="https://media-cdn.tripadvisor.com/media/photo-s/0e/eb/ad/3d/crazy-cat-cafe.jpg" alt="" class="image">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Chairman_Meow_Bao.jpg/1200px-Chairman_Meow_Bao.jpg" alt="" class="image">
<img src="https://static.scientificamerican.com/sciam/cache/file/92E141F8-36E4-4331-BB2EE42AC8674DD3_source.jpg" alt="" class="image">
<img src="https://cdn.britannica.com/91/181391-050-1DA18304/cat-toes-paw-number-paws-tiger-tabby.jpg" alt="" class="image">
<img src="https://www.orlandocatcafe.com/wp-content/uploads/2020/07/14.png" alt="" class="image">
</div>
Unfortunately, I couldn't figure out how to loop the images. Can you help me understand how to do it? Do you think my approach can be a good one? or would you recommend other ways to get that effect?
Thanks!
Use for loop when you go through all images to set their width to their initial value. Also add extra three images from start of the carousel so there wouldn't be empty space when it comes to an end.
var testArray = document.querySelectorAll(".image");
var totImg = testArray.length;
var contIterazioni = 0;
var test = testArray[contIterazioni];
var bounding = test.getBoundingClientRect();
var imgsWidths = []
window.onload = () => {
for(i = 0; i < testArray.length; i++) {
imgsWidths[i] = testArray[i].width
}
}
function galleryScroll() {
test = testArray[contIterazioni];
bounding = test.getBoundingClientRect();
if (bounding.left == 0) {
if (test.width > 0) {
test.width = test.width - 2;
} else {
contIterazioni = contIterazioni + 1;
if (contIterazioni >= totImg - 3){
for(i = 0; i < testArray.length; i++) {
testArray[i].width = imgsWidths[i]
}
contIterazioni = 0;
}
}
}
window.requestAnimationFrame(galleryScroll)
}
window.requestAnimationFrame(galleryScroll);
body{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
width: 100vw;
height: 100vh;
display: flex;
overflow: hidden;
}
<div class="container">
<img src="https://media-cdn.tripadvisor.com/media/photo-s/0e/eb/ad/3d/crazy-cat-cafe.jpg" alt="" class="image">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Chairman_Meow_Bao.jpg/1200px-Chairman_Meow_Bao.jpg" alt="" class="image">
<img src="https://static.scientificamerican.com/sciam/cache/file/92E141F8-36E4-4331-BB2EE42AC8674DD3_source.jpg" alt="" class="image">
<img src="https://cdn.britannica.com/91/181391-050-1DA18304/cat-toes-paw-number-paws-tiger-tabby.jpg" alt="" class="image">
<img src="https://www.orlandocatcafe.com/wp-content/uploads/2020/07/14.png" alt="" class="image">
<img src="https://media-cdn.tripadvisor.com/media/photo-s/0e/eb/ad/3d/crazy-cat-cafe.jpg" alt="" class="image">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Chairman_Meow_Bao.jpg/1200px-Chairman_Meow_Bao.jpg" alt="" class="image">
<img src="https://static.scientificamerican.com/sciam/cache/file/92E141F8-36E4-4331-BB2EE42AC8674DD3_source.jpg" alt="" class="image">
</div>
While keeping your same approach, this should work similarly as the example you provided. If you want the slideshow to keep it's width, all images should have the same width. Your error was not adding back the image that dissapeared to the container, at the end and with it's original width, or as in this case expanding again.
// From https://www.javascripttutorial.net/javascript-queue/
function Queue() {
this.elements = [];
}
Queue.prototype.enqueue = function(e) {
this.elements.push(e);
};
Queue.prototype.dequeue = function() {
return this.elements.shift();
};
Queue.prototype.isEmpty = function() {
return this.elements.length == 0;
};
Queue.prototype.peek = function() {
return !this.isEmpty() ? this.elements[0] : undefined;
};
Queue.prototype.length = function() {
return this.elements.length;
}
let images = new Queue();
document.querySelectorAll(".image").forEach(img => images.enqueue(img));
var totImg = images.length();
var first = images.dequeue();
var last;
var firstWidth = first.width;
var lastWidth = 0.0;
var bounding = first.getBoundingClientRect();
var originalWidth = first.width;
var lastOriginalWidth = 0.0;
var step = 1.0;
var lastStep = 0.0;
function LoopFunction() {
setInterval(galleryScroll, 20);
}
function galleryScroll() {
bounding = first.getBoundingClientRect();
if (bounding.left == 0) {
//console.log("immagine bordo sx");
if (first.width > 0) {
firstWidth -= step;
if (firstWidth < 0) {
firstWidth = 0;
}
first.style.width = firstWidth + 'px';
} else {
if (last && last.width != lastOriginalWidth) {
last.width = lastOriginalWidth;
}
let container = document.querySelector('.container');
container.removeChild(first);
last = first;
lastOriginalWidth = originalWidth;
last.width = 0.0;
lastWidth = 0.0;
images.enqueue(last);
container.appendChild(last);
first = images.dequeue();
originalWidth = first.width;
firstWidth = originalWidth;
lastStep = step * lastOriginalWidth / originalWidth;
}
}
if (last && last.width <= lastOriginalWidth) {
lastWidth += lastStep;
last.style.width = lastWidth + 'px';
if (last.width > lastOriginalWidth) {
last.width = lastOriginalWidth;
}
}
}
LoopFunction();
body {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
width: 100vw;
height: 100vh;
display: flex;
overflow: hidden;
}
<div class="container">
<img src="https://media-cdn.tripadvisor.com/media/photo-s/0e/eb/ad/3d/crazy-cat-cafe.jpg" alt="" class="image">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Chairman_Meow_Bao.jpg/1200px-Chairman_Meow_Bao.jpg" alt="" class="image">
<img src="https://static.scientificamerican.com/sciam/cache/file/92E141F8-36E4-4331-BB2EE42AC8674DD3_source.jpg" alt="" class="image">
<img src="https://cdn.britannica.com/91/181391-050-1DA18304/cat-toes-paw-number-paws-tiger-tabby.jpg" alt="" class="image">
<img src="https://www.orlandocatcafe.com/wp-content/uploads/2020/07/14.png" alt="" class="image">
</div>
Update #1
As requested by OP, here is some further explenation of the changes I made:
I used a simple queue from javascripttutorial to have a data structure that reflects the objective, i.e. having images that move from right to left, and once they "exit" the scene, can get enqueued again.
Following this concept, we need pointers to both head and tail of the queue in order to update their animation, in particular first, firstWidth and originalWidth are used respectively to point to the head, keep track of its current width during the animation and the originalWidth to which it should return when re-entering the scene. Similarly, this happens for the last as well.
Once this is in place, our loop will be made of two parts, one that handles the head animation and moves the images in the queue when the head image reaches width == 0 and one that handles the tail re-entering the scene and expanding. To achieve continuity, we use a simple proportion after we have our new queue: step : originalWidth = lastStep : lastOriginalWidth, which we use to determine at each frame how much respectively the head and tail images compress and expand. as step is a fixed parameter, lastStep is easily computed through simple arithmetics: lastStep = step * lastOriginalWidth / originalWidth.
The code:
let container = document.querySelector('.container');
container.removeChild(first);
last = first;
lastOriginalWidth = originalWidth;
last.width = 0.0;
lastWidth = 0.0;
images.enqueue(last);
container.appendChild(last);
first = images.dequeue();
originalWidth = first.width;
is just a contextual switch over the changing the queue, where the pointers and respective data get update to reflect the changes in the data structure. So the first becomes last, the next image in the queue is the new compressing first, as such originalWidth shifts.
Let's go further
Now, to achieve your desired implementation, this still needs some work. First of all, the queue should only reflect the actual carousel, not all the images you have, so ideally you would have a first static data structure with all the images and respective metadata, in this case we mainly need their original width. then you would have a queue representing the images that are being animated.
Now, you can either reuse this code and change the width of the images to be all equal and fit the viewport you are using for your animation, which should work fine. The other option is to mirror the code for the head image to the tail, have a fixed step, so while the head compresses of step pixels, the tail expands of the same step pixels, and when the tail reaches maximum width, introduce a new image at the end of the queue which becomes the new tail.
To go in further detail on the last, the algorithm would look something like this:
initialize static list of image containers with their respective width (imgList);
initialize an empty queue (imgQueue);
initialize a pointer pointing to the last image introduced in the queue (listPtr);
get the width of the viewport your carousel should fill (vpWidth);
while you have not filled such width, keep adding images to the queue and moving the listPtr left in the imgList;
have looping function similar to the one above but where the if over last replicates similar steps to the first ones;
This should be everything, I will work on the code in a while, now I need some sleep ;).
Update #2
Okay! Worked out something that actually works decently. If you have suggestions please let me know, in the meanwhile, here it is:
// From https://www.javascripttutorial.net/javascript-queue/
function Queue() {
this.elements = [];
}
Queue.prototype.enqueue = function(e) {
this.elements.push(e);
};
Queue.prototype.dequeue = function() {
return this.elements.shift();
};
Queue.prototype.isEmpty = function() {
return this.elements.length == 0;
};
Queue.prototype.first = function() {
return !this.isEmpty() ? this.elements[0] : undefined;
};
Queue.prototype.length = function() {
return this.elements.length;
};
// Added function to peek last element in queue
Queue.prototype.last = function() {
return !this.isEmpty() ? this.elements[this.elements.length - 1] : undefined;
};
// Added function that pops the head, enqueues it and returns it
Queue.prototype.shift = function() {
const head = this.dequeue();
this.enqueue(head);
return head;
}
// Returns a queue of HTMLElements based on the given class
function loadQueue(className) {
const rQueue = new Queue();
document.querySelectorAll('.' + className).forEach(image => rQueue.enqueue(image));
return rQueue;
}
// Queue of images to be added to the animation queue
const imgQueue = loadQueue('image');
// Images being animated inside the div
const imgAnimQueue = new Queue();
// To limit calls to the carousel
const carousel = $('.container');
function init() {
// Width of the viewport being used for the animation
// TODO: this shoud update whenever the page is resized, or at least the div
const vpWidth = carousel.width();
// Keeps track of the width of the images added to the animation queue
var currentFilledWidth = 0;
// Now that we have loaded the static information, let's clear the div
// that will be used as carousel, so that we can add the correct number
// of images back in
carousel.empty();
// Filling the animation queue
while (currentFilledWidth < vpWidth) {
// In order not to change the static data, we clone the image HTMLElement
const img = $(imgQueue.shift()).clone();
// Enqueuing the new image in the animation queue
imgAnimQueue.enqueue(img);
// Adding this image into the carousel
img.appendTo(carousel);
currentFilledWidth = currentFilledWidth + img.width();
// If we overflow the carousel width, we set the tail image to fill
if (currentFilledWidth > vpWidth) {
const overflow = currentFilledWidth - vpWidth;
img.width(img.width() - overflow);
currentFilledWidth -= overflow;
}
}
const step = 1;
var firstWidth = imgAnimQueue.first().width();
var lastWidth = imgAnimQueue.last().width();
// Now the loop can start
window.requestAnimationFrame(animateCarousel);
// Main function that animates the carousel
function animateCarousel() {
let first = imgAnimQueue.first();
let last = imgAnimQueue.last();
// If the image is still not disappeared, keep compressing it
if (firstWidth > 0) {
firstWidth -= step;
if (firstWidth < 0) firstWidth = 0;
first.width(firstWidth);
// Otherwise, remove it from the carousel and update all the data structs
} else {
first.remove();
imgAnimQueue.dequeue();
if (imgAnimQueue.first() != last) {
first = imgAnimQueue.first();
firstWidth = first.width();
} else {
first = last;
firstWidth = lastWidth;
imgAnimQueue.enqueue($(imgQueue.shift()).clone());
last = imgAnimQueue.last();
lastWidth = last.width();
last.appendTo(carousel);
}
}
if (lastWidth <= last.attr("data-original-width")) {
lastWidth += step;
// The image has completely expanded, let's introduce the next one
if (lastWidth >= last.attr("data-original-width")) {
last.width(last.attr("data-original-width"));
imgAnimQueue.enqueue($(imgQueue.shift()).clone());
last = imgAnimQueue.last();
last.width(0);
lastWidth = last.width();
last.appendTo(carousel);
// Otherwise just keep expanding it
} else {
last.width(lastWidth);
}
}
window.requestAnimationFrame(animateCarousel);
}
}
body {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
width: 100vw;
height: 100vh;
display: flex;
overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var loadedImages = 0;
const count = 4;
function loadImage(img) {
if (loadedImages != count) {
$(img).attr("data-original-width", $(img).width());
loadedImages += 1;
if (loadedImages == count) init();
}
}
</script>
<div class="container">
<img onload="loadImage(this)" src="https://media-cdn.tripadvisor.com/media/photo-s/0e/eb/ad/3d/crazy-cat-cafe.jpg" alt="1" class="image">
<img onload="loadImage(this)" src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Chairman_Meow_Bao.jpg/1200px-Chairman_Meow_Bao.jpg" alt="2" class="image">
<img onload="loadImage(this)" src="https://cdn.britannica.com/91/181391-050-1DA18304/cat-toes-paw-number-paws-tiger-tabby.jpg" alt="3" class="image">
<img onload="loadImage(this)" src="https://www.orlandocatcafe.com/wp-content/uploads/2020/07/14.png" alt="4" class="image">
</div>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to turn the banner image on this page into a slide show. I know how to write HTML and CSS but I'm less adept at scripting.
My idea is to have the text stay in place while the the banner image behind it is replaced. I would like to see the new image fade in.
How can I implement this with JavaScript or jQuery?
I implemented a simple fade-out/fade-in slide show for you. The demonstration below uses the three large files you specified in your comments. The slide show won't work until the images have been loaded, so you may want to work on improving the load times.
To use this slide show in your project, merge the CSS rules below into your CSS file, then insert the JavaScript into your page and modify the parameters slideDelay, fadeLength, and imageSources to suit your needs.
SlideShow = {
slideDelay: 5, // Number of seconds to wait before showing a new slide.
fadeLength: 1, // Number of seconds to spend fading in or fading out.
hertz: 60 // Number of times per second to update the fade effect.
};
SlideShow.imageSources = [
'http://preview.impactdesigns-ad.com/HBP/img/basecamp009.jpg',
'http://preview.impactdesigns-ad.com/HBP/img/biohazard007.jpg',
'http://preview.impactdesigns-ad.com/HBP/img/Header.png'
];
SlideShow.showSlide = function (newImage, oldImage) {
var g = SlideShow,
opacityIncrement = 1 / g.hertz,
fade = { interval: {}, count: {} };
function fadeOut() { // Gradually makes the old image vanish.
oldImage.style.opacity = fade.count.out * opacityIncrement;
if (--fade.count.out == 0) {
window.clearInterval(fade.interval.out);
oldImage.style.visibility = 'hidden';
}
}
function fadeIn() { // Gradually makes the new image appear.
newImage.style.opacity = 1 - fade.count.in * opacityIncrement;
if (--fade.count.in == 0) {
window.clearInterval(fade.interval.in);
}
}
function newSlide() { // Starts the fade-in process.
newImage.style.opacity = 0;
newImage.style.visibility = 'visible';
fade.count.in = g.hertz;
fade.interval.in = window.setInterval(fadeIn, g.fadeLength * 1000 / g.hertz);
}
if (oldImage) { // Fade out the old, then fade in the new.
window.setTimeout(newSlide, g.fadeLength * 1000);
fade.count.out = g.hertz;
fade.interval.out = window.setInterval(fadeOut, g.fadeLength * 1000 / g.hertz);
} else { // If there is no old image, immediately fade in the new image.
newSlide();
}
}
SlideShow.replaceSlide = function () { // Updates slideIndex and calls showSlide.
var g = SlideShow,
images = g.images,
oldImage = images[g.slideIndex];
g.slideIndex = ++g.slideIndex % images.length;
var newImage = images[g.slideIndex];
g.showSlide(newImage, oldImage);
};
SlideShow.stop = function () {
var g = SlideShow,
interval = g.interval;
window.clearInterval(interval);
}
SlideShow.start = function () {
var g = SlideShow,
imageSources = g.imageSources,
images = g.images = [],
container = document.getElementById('slideContainer'),
background = g.background = document.createElement('div');
background.className = 'background';
for (var i = 0; i < imageSources.length; ++i) {
var image = document.createElement('img');
image.src = imageSources[i];
image.style.visibility = 'hidden';
images.push(image);
background.appendChild(image);
}
container.appendChild(background);
var startInterval = window.setInterval(function () {
for (var i = 0; i < images.length; ++i) {
if (images[i].height == 0) { // Wait until all images are loaded.
return;
}
}
window.clearInterval(startInterval);
g.slideIndex = 0;
g.showSlide(images[g.slideIndex]);
g.interval = window.setInterval(g.replaceSlide, g.slideDelay * 1000);
}, 100);
};
SlideShow.start();
#slideContainer {
font-family: sans-serif;
font-weight: bold;
font-style: italic;
font-size: 48px;
color: #cb4949;
width: 1000px;
height: 700px;
overflow: hidden;
position: relative;
}
#slideContainer span {
padding: 20px;
text-align: center;
position: absolute;
z-index: 10;
}
#slideContainer .background, #slideContainer .background img {
position: absolute;
left: 0;
top: 0;
}
<div id="slideContainer"> <span>This is some text over the slide.</span> </div>
<button onclick="SlideShow.stop()"> stop slide show </button>
I have the following hacked code to fadein text and fadeout an image on hover. I want to repeat this affect on a second image/div but I can't get it to work. i tried copying all the scripting and changing the variable names (i.e. img2 instead of img1 etc.) and I tried adding multiple handlers to the existing code but it doesn't work. Only one image will fade while the other one does not. Please help. If it is not abdunantly clear, I am a Jquery wannabe who has some HTMl skills and a rudimentary understanding of programming. Thanks
<style type="text/css">
#imgContainer {
position: relative;
}
#img1 {
opacity: 100;
filter:alpha(opacity=100);
position: relative;
top: 0px;
left: 0px;
}
#imgContainer div {
position: absolute;
top: 20px;
left: 60px;`enter code here`
}
</style>
<script type="text/javascript">
var speed = 0.8;
var fadeTimerImg, fadeTimerTxt;
function fade(obj,dir){
if(fadeTimerImg){clearInterval(fadeTimerImg);}
if(fadeTimerTxt){clearInterval(fadeTimerTxt);}
fadeTimerImg = setInterval(function(){setOpacity(obj,dir)},100);
fadeTimerTxt = setInterval(function(){setOpacity(oTxtContainer,-dir)},100);
}
function setOpacity(obj,dir) {
obj.curOpac = obj.curOpac + (speed * dir);
if(obj.curOpac < 0){obj.curOpac = 0;}
if(obj.curOpac > 10){obj.curOpac = 10;}
if(typeof(obj.style.opacity) == 'string'){
obj.style.opacity = obj.curOpac/10;
} else {
obj.style.filter = 'alpha(opacity=' + obj.curOpac*10 + ')';
}
}
window.onload=function(){
var oImg1 = document.getElementById('img1');
oImg1.curOpac = 10; //10 = opaque
oTxtContainer = document.getElementById('txtContainer');
oTxtContainer.curOpac = 0; //0 = transparent
oImg1.onmouseover = function(){fade(this,-1);}
oImg1.onmouseout = function(){fade(this,1);}
}
</script>
<div id="imgContainer">
<div id="txtContainer">
s`enter code here`ome text<br />
more text <br />
some more text
</div>
<img id="img1" src="FRY751_A.jpg">
</div>
Add the same class to each image, and do this, for example:
window.onload=function(){
var $images = $('.my-image-class');
$images.each(function() {
$(this).curOpac = 10; //10 = opaque
$(this).onmouseover = function(){fade(this,-1);}
$(this).onmouseout = function(){fade(this,1);}
});
}
I am trying to randomise a image in a background, I am having problems because there is content already in the div
this is what i got so far
<div class="welcome-inner">
<script type="text/javascript">
<!--
var imlocation = "welcome/";
var currentdate = 0;
var image_number = 0;
function ImageArray (n) {
this.length = n;
for (var i =1; i <= n; i++) {
this[i] = ' '
}
}
image = new ImageArray(3)
image[0] = 'background1.jpg'
image[1] = 'background2.jpg'
image[2] = 'background3.jpg'
var rand = 60/image.length
function randomimage() {
currentdate = new Date()
image_number = currentdate.getSeconds()
image_number = Math.floor(image_number/rand)
return(image[image_number])
}
document.write("<img src='" + imlocation + randomimage()+ "'>");
//-->
</script>
CONTENT
</div>
the div welcome-inner already has styling in the css
.row-welcome {
border-bottom: 0;
width: 100%;
margin: 0 auto;
overflow: auto;
margin-top: -20px;
background-position: 50% 50%;
background-size: cover;
border-bottom: 1px solid #1e346a;
}
welcome-inner did have a background image but I removed the line to try to get this to work
The problem I am having is that the images are showing up but pushing my content down.
how do I adapt this to make it work?
You're going to need to set the background-image style (if you're using jQuery this will be easier). So, instead of creating an tag which goes in the normal document flow, something more like this:
$("#welcome-inner").style("background-image", imlocation + randomimage());
And change "#welcome-inner" to whatever the selector is for the DOM element you want to set the background-image on.
I think your entire approach is incorrect. Try using .sort(), like:
var doc = document;
function E(e){
return doc.getElementById(e);
}
function range(least, greatest){
var r = [];
for(var i=0,n=least; n<=greatest; i++,n++){
r[i] = n;
}
return r;
}
var rng = range(1, 3);
rng.sort(function(){
return Math.round(Math.random())-0.5;
});
for(var i in rng){
var img = new Image();
img.src = 'welcome/background"+rng[i]+".jpg';
// If you add an id called pickAnId to your welcome-inner className div then
E('pickAnId').appendChild(img);
}
I am working on a wordpress website who's client would like me to adjust our AdSanity plugin to display groups of ads in a rotating image gallery fashion like the ones on this page. The leaderboard ads for sure are AdSanity run. I was able to stem from viewing the source that this is the script I need:
$(function() {
var adsLists = $('.adsanity-group'),
i = 0;
var divs = new Array();
adsLists.each(function() {
divs[i] = $("#" + $(this).attr('id') + " div").not(".clearfix").hide();
i++;
});
var cycle_delay = 12000;
var num_groups = $('.adsanity-group').length;
function cycle(divsList, i) {
divsList.eq(i).fadeIn(400).delay(cycle_delay).fadeOut(400, function() {
cycle(divsList, ++i % divsList.length); // increment i, and reset to 0 when it equals divs.length
});
};
for (var j = divs.length - 1; j >= 0; j--) {
if (divs[0].eq(0).attr('num_ads') > 1)
cycle(divs[j], 0);
else
divs[j].show();
};
//////////
$('#slides').slidesjs({
width: 552,
height: 426,
navigation: false,
play: {
auto: true
}
});
//////////
$('.three_lines_fixed').each(function() {
$clamp(this, {
clamp: 3
});
});
var top_divs = $("#adspace div").not(".clearfix").hide(),
top_i = 0;
var top_num_ads = $('#adspace > div').attr("num_ads");
var top_cycle_delay = 12000;
function top_cycle() {
top_divs.eq(top_i).fadeIn(400).delay(top_cycle_delay).fadeOut(400, top_cycle);
top_i = ++top_i % top_divs.length; // increment i,
// and reset to 0 when it equals divs.length
};
if (top_num_ads > 1) {
top_cycle();
} else {
top_divs.show();
}
var site_url = $("body").attr("site_url");
$("#brpwp_wrapper-2 ul").append("<li style='text-align: center;'><a class='widgetized_read_more' href='" + site_url + "/2013'>Read More</a></li>")
/**/
And some of that I don't believe I need, like the three_lines_fixed or the slides. I also have the CSS used for #adspace:
div.header div#adspace {
float: right;
max-width: 728px;
max-height: 90px; }
div.header div#adspace img {
float: right; }
There is also this CSS:
div#page .main_content ul.widgets li.adspace {
display: none; }
On my site http://dsnamerica.com/eisn/ I want the 300px width ads on the right sidebar to rotate like those on the Vype site. These ads though are not listed with ul and li, they are divs.
So far I've added this to my header.php theme file right before the closing tag:
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/fading-ads.js"></script>
And in that file (js/fading-ads.js), I have this:
function adsanitygroup() {
var adsLists = $('.adsanity-group'),
i = 0;
var divs = new Array();
adsLists.each(function() {
divs[i] = $("#" + $(this).attr('id') + " div").not(".clearfix").hide();
i++;
});
var cycle_delay = 12000;
var num_groups = $('.adsanity-group').length;
function cycle(divsList, i) {
divsList.eq(i).fadeIn(400).delay(cycle_delay).fadeOut(400, function() {
cycle(divsList, ++i % divsList.length); // increment i, and reset to 0 when it equals divs.length
});
};
for (var j = divs.length - 1; j >= 0; j--) {
if (divs[0].eq(0).attr('num_ads') > 1)
cycle(divs[j], 0);
else
divs[j].show();
var top_divs = $("#adspace div").not(".clearfix").hide(),
top_i = 0;
var top_num_ads = $('#adspace > div').attr("num_ads");
var top_cycle_delay = 12000;
function top_cycle() {
top_divs.eq(top_i).fadeIn(400).delay(top_cycle_delay).fadeOut(400, top_cycle);
top_i = ++top_i % top_divs.length; // increment i,
// and reset to 0 when it equals divs.length
};
if (top_num_ads > 1) {
top_cycle();
} else {
top_divs.show();
};
};
}
That is my attempt to define the function and clean out what I didn't need. I don't think, no, I know it's not right. So I'll put my questions in a list, since this post is already wordy.
1) Did I link the js file correctly in the theme's header.php file? It's right before the closing </head> tag.
2) Do I need the second CSS part that says "display: none" and if so, how do I change the CSS to work with divs instead of ul and li? Do I just change div#page .main_content ul.widgets li.adspace {
display: none;}
to
div#page .main_content .widgets .adspace {
display: none; }
then add the class .adspace to the widget?
See, I have been trying to get this to work for a couple days now and I've thought so much on it I'm not making cohesive theories anymore, just shots in the dark. How to solve this?