Button image change on a timer - javascript

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.

Related

Same random color on multiple pair of divs

So, I have a code where I generate a random color on page load.
$(function() {
$(".stuff").each(function() {
var hue = 'rgb('
+ (Math.floor((256)*Math.random()) + 25) + ','
+ (Math.floor((256)*Math.random()) + 25) + ','
+ (Math.floor((256)*Math.random()) + 25) + ')';
$(this).css("background-color", hue);
});
});
The color applies to the div .stuff. This div .stuff, works as a button. When I click .stuff, a relating div opens, which I call .filling.
.filling is not displayed on page load. When I click .stuff, both .stuff and .filling is displayed.
I have several .stuff, relating to their each .filling, creating pairs, so to speak.
The html:
<div id="port1Btn" class="divClick stuff">
</div>
<div id="port1" class="filling">
<img src="img/hyper.png">
</div>
The #port1Btn and #port1 is for defining the content of each pair, connecting them to the right button. And the divClick is for a script that helps close a open .filling when a .stuff is clicked.
Here is the code for that, if needed:
$('.divClick').bind("click", showFilling);
function showFilling(event) {
event.preventDefault();
var amountOfPorts = 999;
var ports = "";
for (i=0;i<amountOfPorts;i++) {
ports += "#port" + (i+1) +",";
}
ports = ports.slice(0, -1);
$(ports).hide();
var clickDiv = "#" + event.currentTarget.id;
var targetDiv = clickDiv.replace('Btn','');
$(targetDiv).toggle(100);
};
So, what I want to do is to have .stuff and .filling have their same color for each pair, but at the same time, every pair should have a different, random color on page load.
Thank you for reading, hope it was not too long, if so, let me know for future posts.
You can use the next() function.
$(function() {
$(".stuff").each(function() {
var hue = 'rgb('
+ (Math.floor((256)*Math.random()) + 25) + ','
+ (Math.floor((256)*Math.random()) + 25) + ','
+ (Math.floor((256)*Math.random()) + 25) + ')';
$(this).css("background-color", hue);
$(this).next(".filling").css("background-color",hue);
});
});
Adding that line will set the next div in the DOM after '.stuff' with the '.filling' class to the same color.

Modifying an X and Y variable, based on position in For Loop

EDIT - I don't think I explained it very well the first time.
I have a lot of data - it's in an Array, with each item in the array being an object. In the system I am working in (a control system for A/V devices, which uses JavaScript as the programming language), I am generating buttons based on the length of the array. I want to be able to position a button, and essentially know the X and Y coordinates for each button in the array - with X and Y being Row/Column. (which I then translate to a X/Y pixel position on my UI.
My initial code, which is below, is within a for loop, and I manually calculated the button position. But this is tedious, as I use this same function to show off different groups/sizes of buttons.
Anywhere there is mirage.log = console.log.
The code below is part of a For Loop
button.element.style.position = 'absolute'; //Do to all Buttons.
if (i == 0) //First Item
{
button.element.style.left = btn_Info.startLeft + 'px'; button.element.style.top = btn_Info.startTop + 'px';
}
else if (i <= btn_Info.numRow-1) //First Column.
{
mirage.log('Setting Position of First Column');
button.element.style.left = btn_Info.startLeft + 'px'; button.element.style.top = (btn_Info.height + btn_Info.vOffset) * i + btn_Info.startTop + 'px';
}
else if (i > btn_Info.numRow - 1 && i <= btn_Info.numRow * 2 - 1)
{
mirage.log('Setting Second column ' + i);
button.element.style.left = btn_Info.startLeft + btn_Info.width + btn_Info.hOffset + 'px'; button.element.style.top = (btn_Info.height + btn_Info.vOffset) * (i-btn_Info.numRow) + btn_Info.startTop + 'px';
}
else
{
mirage.log('Setting Third column ' + i);
button.element.style.left = btn_Info.startLeft + ((btn_Info.width + btn_Info.hOffset)*2) + 'px'; button.element.style.top = (btn_Info.height + btn_Info.vOffset) * (i - (btn_Info.numRow*2)) + btn_Info.startTop + 'px';
}
Thanks in advance for the help - I have grabbed so many answers from this forum over the last year, you guys are awesome!
EDIT -
I was able to get some adjustment if I generate rows first then columns:
I was able to get a little close with the help of a friend, and be able to adjust for a 2 column layout by doing the following:
encoder = {
'buttonVals':{'width':125,'height':50,'numCols':2,'numRows':null;'vOffset':10,'hOffset':10}
var posLeft;
var posTop;
posLeft = (i % encoder.buttonVals.numCols) * (encoder.buttonVals.width + encoder.buttonVals.hOffset) + encoder.buttonVals.startLeft;
posTop = Math.floor(i / encoder.buttonVals.numCols) * (encoder.buttonVals.height + encoder.buttonVals.vOffset) + encoder.buttonVals.startTop;
After working on this for a bit - here is the code that I got to work. This prints out both the row position, and the column position.
testFunction = function(incRow, incCol){
var myFunc = {
'testLength':0,
'numRows':incRow,
'numCols':incCol,
'array':[],
};
myFunc.testLength = incRow * incCol;
for(var c=0, posCol = 0, posRow = 0; c < myFunc.testLength; c++)
{
var whichRow;
posRow = Math.floor(c/myFunc.numRows);
whichRow = Math.floor(c/myFunc.numRows) + c;
if (whichRow > myFunc.numRows)
{
whichRow = whichRow - (myFunc.numRows * posRow) - posRow;
if (whichRow === 0)
{
posCol = posCol + 1;
}
}
console.log(c + ' : ' + whichRow + ' : ' + posCol);
}
};
testFunction(6,4);

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 Prevent Loading same image twice in a row

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

"error CS1012: Too many characters in character literal"

i have a JavaScript code of photo gallery with a slider but there's a problem :
var partnum = "<%Response.Write(Request.QueryString["partno"]); %>";
// check if the file is exiset -- it's running in bar() function -- run on servers and local host.
function UrlExists(url) {
var http = new XMLHttpRequest();
http.open('GET', url, false);
http.send();
return http.status != 404;
}
// push images paths to array
function bar() {
var exict = 0;
var counter = 0; //counter of array's index
for (var i = 1 ; exict < 30; i++) {
// if there isn't .jpg or .gif
if (!UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".jpg") && !UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".gif")) {
exict = exict + 1;
}
// if there is .jpg
if (UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".jpg") && !UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".gif")) {
arrOfImgs.push("/assets/catalog/parts/" + partnum + "_" + i + ".jpg");
counter = counter + 1;
}
// if there is .gif
if (UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".gif") && !UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".jpg")) {
arrOfImgs.push("/assets/catalog/parts/" + partnum + "_" + i + ".gif");
gifIndex.push(i);
counter = counter + 1;
}
}
}
but it was not work, so i tried to change var partnum
var partnum = <%= new JavaScriptSerializer().Serialize(Request.QueryString['partno']) %>;
but I got error: "error CS1012: Too many characters in character literal". I'm still not sure that this is the issue, as my original code does work (you can see the initial product image loaded when you visit the site .baumhaus and click on a product range and then any product, you will see the action - before it disappears once it tries to render the thumbnails).
How about
var partnum = '<%= Request.QueryString["partno"] %>'";

Categories

Resources