jQuery Prevent Loading same image twice in a row - javascript

I am using a good bit of jQuery to create a CSS fade effect on a website. It works really well. But as it only has 4 images in the array, It is quite likely loading the same image twice in a row.
What can I add to prevent this?
My current jQuery code is as follows :
// Playthrough Background Images
var imgArray = ['http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img/home/banner1.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img//home/banner2.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img//home/banner3.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img/home/banner4.jpg'
]
var nextBG = "url(" + imgArray[Math.floor(Math.random() * imgArray.length)] + ")";
$('#header.home-page').css("background-image", nextBG);
setInterval(function(){
nextBG = "url(" + imgArray[Math.floor(Math.random() * imgArray.length)] + ")";
$('#header.home-page').fadeOut('fast', function() {
$(this).css("background-image", nextBG).fadeIn('fast'); })
}, 4000); // 4 second interval
Thanks in advance.
Cheers

You can show your images one after another (and repeat this the whole time):
var counter = 0;
// Playthrough Background Images
var imgArray = ['http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img/home/banner1.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img//home/banner2.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img//home/banner3.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img/home/banner4.jpg'
]
var nextBG = "url(" + imgArray[counter] + ")";
$('#header.home-page').css("background-image", nextBG);
setInterval(function(){
counter++;
nextBG = "url(" + imgArray[counter % imgArray.length] + ")";
$('#header.home-page').fadeOut('fast', function() {
$(this).css("background-image", nextBG).fadeIn('fast'); })
}, 4000); // 4 second interval
or choose randomly:
// Playthrough Background Images
var imgArray = ['http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img/home/banner1.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img//home/banner2.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img//home/banner3.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img/home/banner4.jpg'
]
var current = Math.floor(Math.random() * imgArray.length);
var nextBG = "url(" + imgArray[current] + ")";
$('#header.home-page').css("background-image", nextBG);
setInterval(function(){
var copy = imgArray.slice(0); // make copy
copy.splice(current, 1); // remove current
current = Math.floor(Math.random() * copy.length);
nextBG = "url(" + copy[current] + ")";
$('#header.home-page').fadeOut('fast', function() {
$(this).css("background-image", nextBG).fadeIn('fast'); })
}, 4000); // 4 second interval

Related

Set width dynamically in .each - JS

I have a problem in setting width of an element dynamically. I have multiple .each loops and then I append an element which should have calculated width. This is the code I have
$.each(roomsArray, function(index, row) {
$.each(datesArray, function (dateIndex, date) {
$.each(row.calendarList, function(calendarIndex, cal) {
if(cal.roomId == row.id && new Date(cal.dateFrom).toDateString() == new Date(date).toDateString()) {
var cellElements = $(".day[data-date='" + new Date(date).toDateString() + "']");
$.each(cellElements, function (indexElement, element) {
if (element.parentElement.attributes[1].value == cal.roomId) {
var to = new Date(cal.dateTo);
var from = new Date(cal.dateFrom);
//the width should be 44*numOfDays
var numOfDays = Math.ceil((to.getTime() - from.getTime()) / (1000 * 3600 * 24));
console.log(element);
$(element).append(`
//This element needs to take the width
<div id="` + element.attributes[0].value + element.attributes[1].value + `" class="draggable"></div>
`);
//This is just something I tried to do, but it doesnt work.
$('#' + element.attributes[0].value + element.attributes[1].value).css('width', 44 * numOfDays + 'px');
}
});
}
});
})
});
Thanks for help in advance!
Try this fiddle: http://jsfiddle.net/TrrCh/
I think you are trying to run the Javascript before the HTML is loaded. Bind it to the document.ready and it should be working
window.onload=function(){
var elem = document.getElementById('chart');
elem.style.width = 70 + "%";
}

JQuery background URL uncaught syntax error

I'm trying to make a background slideshow using jQuery. I'm trying to have a hidden div (nextDiv) on the right of activeDiv slide nextDiv over activeDiv so that activeDiv will be overlapped by nextDiv. Once that is done, the background of nextDiv will then be changed to prepare for the new background image. Below is the code I have written.
// Scroll background
var bgClicked = false;
var bgList = [];
$(".bg-img").each(function(idx, el) {
bgList.push($(el).css('background-image').substr(4, 50));
bgList[idx] = bgList[idx].substr(0, bgList[idx].length -1);
});
var bgNum = bgList.length;
var bgNextDiv = $("#bg-next");
var bgActiveDiv = $("#bg-active");
var bgActive = 0;
var bgNext = 1;
// Scroll until clicked
console.log(bgList);
if(bgClicked == false) {
setInterval(function() {
$(bgList[bgNext]).animate({left:0}, 1000, 'linear', function() {
bgActiveDiv.css('background-image', 'url(' + bgList[bgNext] + ')');
bgActive = bgNext;
bgNext = bgNext < bgNum - 1 ? bgNext + 1 : 0;
bgNextDiv.css('background-image', 'url(' + bgList[bgNext] + ')');
});
}, 5000);
}
However, I'm getting
Uncaught Error: Syntax error, unrecognized expression: http://localhost:3000/img/bg2_2560x1440px.jpg`
when setting
bgActiveDiv.css('background-image', 'url(' + bgList[bgNext] + ')');
I think I missed something, but I don't know where.
Please help?
Cheers,
Agi
EDIT 1
Content of bgList = ["http://localhost:3000/img/bg1_2560x1440px.jpg", "http://localhost:3000/img/bg2_2560x1440px.jpg"]
You are using bgList[bgNext] as jQuery selector that is why you are getting error.
So, use this instead:
$(".bg-img:eq(" + bgNext + ")").animate({left:0}, 1000, 'linear', function() {
bgActiveDiv.css('background-image', 'url(' + bgList[bgNext] + ')');
bgActive = bgNext;
bgNext = bgNext < bgNum - 1 ? bgNext + 1 : 0;
bgNextDiv.css('background-image', 'url(' + bgList[bgNext] + ')');
});

Jquery .each() giving me values of all elements with the same class

Please go to: www.designedbychristian.com/template_2
(so far being tested in chrome)
When you click design a bunch of thumbnails appear.
I am trying to use the .each selector to get the src of the image. I want to take that value and apply it to a div that will appear when clicked. (I know how to program that part)
My problem is when I click the thumb nail my alert is giving me the value of all of the thumbnails.
my code is this:
function spawnImages() {
N = 1
for (i = 1; i <= 9; i++) {
var gal = document.getElementById('gallary')
var newDIV = '<img onclick="imageView()" src="images2/image' + N + '.jpg" class="thumb-nail imageNumber' + N + '"/>'
$('.gallary').prepend(newDIV)
var min = 3;
var max = 70;
var s = Math.floor(Math.random() * (max - min + 1)) + min;
var test = $(('.imageNumber' +N)).css("left", s + "%")
var min = 3;
var max = $(this).height();
var max = 70;
var s = Math.floor(Math.random() * (max - min + 1)) + min;
var test = $(('.imageNumber' + N)).css("top", s + "%")
var min = -45;
var max = 45;
var s = Math.floor(Math.random() * (max - min + 1)) + min;
var test = $(('.imageNumber' + N)).css("-webkit-transform", "rotate(" + s + "deg)")
var test = $(('.imageNumber' + N)).css("transform", "rotate(" + s + "deg)")
var test = $(('.imageNumber' + N)).css("-ms-transform", "rotate(" + s + "deg)")
N++
}
}
function imageView() {
$(".thumb-nail").each(function () {
var imageSrc = $(this).attr('src');
alert($(this).attr('src'));
//$('.images').css("background-image", "url("+imageSrc+")");
//$('.images').css("background-size", "cover");
//$('.blackForeground').css("visibility", "visible");
//$('.images').css("visibility", "visible");
})
};
Just use jquery event handlers, get rid of the onclick call in your html and just add this in your javascript.
$(".thumb-nail").on('click', function(){
var imageSrc = $(this).attr('src');
alert($(this).attr('src'));
//$('.images').css("background-image", "url("+imageSrc+")");
//$('.images').css("background-size", "cover");
//$('.blackForeground').css("visibility", "visible");
//$('.images').css("visibility", "visible");
});
EDIT: didn't think about the images being created dynamically, Popnoodles answer is the right one
pass clicked element reference like this:
var newDIV = '<img onclick="imageView(this)" src="images2/image' + N + '.jpg" class="thumb-nail imageNumber' + N + '"/>'
Function:
function imageView(element) {
var imageSrc = $(element).attr('src');
alert($(element).attr('src'));
}
This is exactly how the jQuery API describes the .each() method:
Iterate over a jQuery object, executing a function for each matched element.
When you called $('.thumb-nail') it returned ALL of the elements with the class thumb-nail in a jQuery object. Then when you called .each( function() {} ) on that object, the loop iterated over all of the returned elements.
The easiest way to handle click events in jQuery, is to use the .on() method, as others have pointed out in their answers.
Also, as #Popnoodles mentioned, since these elements are created dynamically, you may need to run your $().on() call explicitly after these elements are created. For that reason, you might wrap it into your spawnImages() function, rather than putting it inside $() as #Popnoodles indicates (i.e. not $( $(element).on('click',function(){}), as $( ) is equivalent to $(document).ready.
The simplest change is this
// send this element to the function
var newDIV = '<img onclick="imageView(this)" src="images2/image' + N + '.jpg" class="thumb-nail imageNumber' + N + '"/>'
function imageView(el) {
var imageSrc = $(el).attr('src');
alert($(el).attr('src'));
};
But it's nice to do things in a more standard fashion...
First get rid of this onclick="imageView()"
var newDIV = '<img src="images2/image' + N + '.jpg" class="thumb-nail imageNumber' + N + '"/>'
Since these elements are created dynamically you will need to bind the click event to document or another ancestor that exists, and delegate to each ".thumb-nail".
You also need to run this procedure only when dom is ready ($(function(){...});).
$(function(){
$(document).on('click', ".thumb-nail", function () {
var imageSrc = $(this).attr('src');
alert($(this).attr('src'));
//$('.images').css("background-image", "url("+imageSrc+")");
//$('.images').css("background-size", "cover");
//$('.blackForeground').css("visibility", "visible");
//$('.images').css("visibility", "visible");
});
});

js body random background image

This code should use any .jpg image from /images/bg/ folder, however it doesn't seems to be taking images below particular resolution...any suggestions?
<!--random background images from a folder-->
<script type="text/javascript">
var totalCount = 5;
function ChangeIt() {
var num = Math.ceil(Math.random() * totalCount);
document.body.background = 'images/bg/' + num + '.jpg';
document.body.style.backgroundSize = "cover";
}
</script>
Demo
document.body.background is deprecated, it should be document.body.style.background and the format you're giving it is wrong. Try
document.body.style.background = 'url(images/bg/' + num + '.jpg)';
The following also works and doesn't remove the other attributes of background, like backgroundSize for example, so you wouldn't need the line document.body.style.backgroundSize = "cover"; as long as it was set in the first place.
document.body.style.backgroundImage = 'url(images/bg/' + num + '.jpg)';
So, your code would read
<script type="text/javascript">
document.body.style.backgroundSize='cover';
document.body.style.backgroundRepeat='no-repeat'; // i've assumed this
var totalCount = 5;
function ChangeIt() {
var num = Math.ceil(Math.random() * totalCount);
document.body.style.backgroundImage = 'url(images/bg/' + num + '.jpg)';
}
</script>
Though, ideally you'd set cover and no-repeat in a CSS file.
Use document.body.style.backgroundImage = "url('" + 'images/bg/' + num + '.jpg' + ")";
(google about css background image).

Button image change on a timer

In my project I have a page which contains 5 image buttons laying horizantally.
When the page loads image on the Button1 should change(remaining 4 buttons remains same).
After 3 seconds Button1 comes back to its original image and image on Button2 will change.
After 3 seconds Button2 comes back to its original image and image on Button3 will change.
And so on..
But After the Button5 is done , It should come back to the Button1 image again.
This should go on in a continuous loop.
Here is my code.But its not working I don't know the reason why its not working.
any help will be appreciated.
Here is my code
$(document).ready(function (){
BeginRotation();
});
function BeginRotation() {
rotateButton(0);
}
function rotateButton(buttonIndex) {
var previousIndex = (buttonIndex + 4) % 5;
var previousCurrentClass = 'main-nav-button' + (previousIndex + 1) + '-on';
var previousNewClass = 'main-nav-button' + (previousIndex + 1);
var currentClass = 'main-nav-button' + (buttonIndex + 1);
var newClass = 'main-nav-button' + (buttonIndex + 1) + '-on';
// alert('Previous Current Class: ' + previousCurrentClass + '\nPrevious New Class: ' + previousNewClass + '\nCurrent Class: ' + currentClass + '\nNew Class: ' + newClass);
$('.' + currentClass).removeClass(currentClass).addClass(newClass);
$('.' + previousCurrentClass).removeClass(previousCurrentClass).addClass(previousNewClass);
window.setTimeout(rotateButton((buttonIndex + 1) % 5), 3000);
}
One thing that is incorrect for sure
window.setTimeout(rotateButton((buttonIndex + 1) % 5), 3000);
It should be
window.setTimeout("rotateButton(" + ((buttonIndex + 1) % 5) + ")", 3000);
I didn't test this code, but something like this should work:
jQuery(function($){
var $btns = $('a.btn');
var index = 0;
setInterval(function() {
$btns.removeClass('rotateThis');
$btns[index].addClass('rotateThis');
index = (index + 1 >= $btns.size()) ? 0 : index + 1;
}, 3000);
});
$('a.btn') being whatever selector works to grab your image buttons of course.

Categories

Resources