cross fade background image on click - javascript

the java script code in here is auto slide images, but i need to convert this as onclick code,when i click .box1 classes.
and when i click box1 classes crosssfade only have to be effect to background image which is in id=#main. cross fade must not effect to box1 and it has to be continuously appeared when background image cross fade.
for crossfade the background image, images have to connect with directly to the image
folder. for that i need to connect with image folder and background image in #main.
can some body help with this.
my code is here
var timer = setInterval(nextImage, 4000);
var curImage = 0;
var numImages = 5;
function nextImage() {
var e;
// remove showMe class from current image
e = document.getElementById("slideimg" + curImage);
removeClass(e, "showMe");
// compute next image
curImage++;
if (curImage > numImages - 1) {
curImage = 0;
}
// add showMe class to next image
e = document.getElementById("slideimg" + curImage);
addClass(e, "showMe");
}
function addClass(elem, name) {
var c = elem.className;
if (c) c += " "; // if not blank, add a space separator
c += name;
elem.className = c;
}
function removeClass(elem, name) {
var c = elem.className;
elem.className = c.replace(name, "").replace(/\s+/g, " ").replace(/^\s+|\s+$/g, ""); // remove name and extra blanks
}

Check the following JSfiddle to change image on clcik
http://jsfiddle.net/arunberti/cwP5Q/99/
Write the function inside the below code
$('#container').click(function() {
});

Related

JavaScript move character. Change image on clicking right arrow

Hi currently I'm making some RPG game. I want to move my character with arrows. Which is working right now. But I want to change image when I clicking let's say the right arrow. Right now when I click right arrow with this code:
function rightArrowPressed() {
var element = document.getElementById("image1").src = "/img/run_1.png";
element = document.getElementById("image1");
element.style.left = parseInt(element.style.left) + 5 + 'px';
}
The image change's to run_1.png ant it stays like that. Than just the image slides in one pose. How to change the image again when I click right arrow ?
HTML
<img id="image1" src="{{Auth::user()->char_image}}" style="position:absolute;left:0; top:0;height: 45px; image-rendering: -webkit-optimize-contrast;">
You can use a counter variable:
var counter = 0;
function rightArrowPressed() {
counter = (counter === 4) ? 1 : counter+1;
var image = "/img/run_"+counter+".png";
var element = document.getElementById("image1");
element.src = image;
var left = parseInt(element.style.left)+5;
element.style.left = left + "px";
}
And this would make it so that every time you right click, a different image is used.
You can use an arry imeges sources to make a scene
function rightArrowPressed() {
var slides=['/img/run_1.png','/img/run_2.png','/img/run_1.png'];
slides.forEach(slide => {
setTimeout(function(){
var element = document.getElementById("image1").src = slide;
element = document.getElementById("image1");
element.style.left = parseInt(element.style.left) + 5 + 'px';
}, 500);//add a time in screen
});
}

Check to see if background image source exists, with an increasing counter?

I'm trying to have an image gallery on my site, where I have a counter in the background image source, and when a button is clicked, the counter goes up, changing the background image.
But I want the counter to reset, if the image file doesn't exist.
How would I achieve this?
HTML
<div></div>
<button>click</button>
Javascript
var div = document.querySelector("div");
var button = document.querySelector("button");
var counter = 1;
div.style.backgroundImage = "url(image1.jpg)";
button.addEventListener("click", function() {
counter++;
div.style.backgroundImage = "url(image" + counter + ".jpg)";
console.log(counter + " " + div.style.backgroundImage);
if (div.style.backgroundImage === undefined) { counter = 1 } // something like this?
});
There are no JS callbacks for css styles. There is no way to know if a background image loaded successfully or not wait plain JS. It is necessary to load the image twice - once to check.
For that, you can use something like this:
function imageExists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, false);
http.send();
return http.status != 404;
}
And refactor your code to pass the image url to the function.
var div = document.querySelector("div");
var button = document.querySelector("button");
var counter = 1;
div.style.backgroundImage = "url(image1.jpg)";
button.addEventListener("click", function() {
counter++;
var imageUrl = "image" + counter;
if (imageExists(imageUrl)){
//Image can be loaded
div.style.backgroundImage = "url(image" + counter + ".jpg)";
console.log(counter + " " + div.style.backgroundImage);
} else {
//Image cannot be loaded
counter = 1;
div.style.backgroundImage = "url(image" + counter + ".jpg)";
}
// something like this?
});

passing array of hyperlinks in jquery

I am creating a flowchart using jquery and html which has nodes(circles) and arrows which connect these circles.. two actions need to be done, one is a tooltip action, which will show a particular text when u hover your cursor on particular circle. And the other function is that whenever we click those circles another html page pops up AKA hyperlinks. I have 18 circles and i hav created desired 18 HTML pages. BUt m stuck at hyperlinking. I dont know how to pass these hyperlinks to my Jquery plugin. Below is an attached code for tooltip function
function oncanvasmousemove(evt) {
clearTimeout(timer);
lastTimeMouseMoved = new Date().getTime();
timer = setTimeout(function () {
var currentTime = new Date().getTime();
if (currentTime - lastTimeMouseMoved > 300) {
var mousePos = getMousePos(canvas, evt);
var tC, isMatched = false;
for (c = 0; c < circles.length; c++) {
tC = circles[c];
if (mousePos.DistanceTo(tC.centerX, tC.centerY) < tC.Radius + 5) {
isMatched = true;
break;
}
}
if (isMatched === true) {
$("#tooltip").html(tC.Text).css({
'top': mousePos.Y + canvasoffset.top - 40,
'left': mousePos.X + canvasoffset.left - $("#tooltip").width() / 2
}).show();
} else {
$("#tooltip").hide();
}
}
}, 300);
}
i am attaching a image of the page
You need to give each circle a CSS ID.
For my example, I will just use "#circle-1", "#circle-2" ... "#circle-18".
Also add a CSS class to every circle. For my example I will use ".circle-link".
//On clicking anything with the circle-link class...
$('.circle-link').click(function() {
var link_id = $(this).attr("id"); //Get ID of circle that was clicked
//Get ID number
link_id = link_id.split("-"); //Split the string on the dash/hyphen (returns array)
link_id = link_id[2]; //Get second array element (should be the number)
//Use the above number to determine which link to call
});

Delay fadeIn() in a for-loop

I created a menu with Jquery FadeIn animation, i want to open the menu when my mouse is hover but i also want to fadein the previous tab content.
This should works like this :
My mouse is one the third tab, the first tab popin, then the second one, then the third with a little delay between each animation.
I tried to do this with Jquery :
$('.navigation li').hover(
// When mouse enters the .navigation element
function () {
var tab = $(this).attr('id');
var numTab = tab.substring(2);
//Fade in the navigation submenu
for ( var i = 0; i <= numTab ; i++ ) {
var domElt = '#Et' + i + ' ul';
$(domElt).fadeIn(300); // fadeIn will show the sub cat menu
console.log(domElt);
}
},
// When mouse leaves the .navigation element
function () {
var tab = $(this).attr('id');
var numTab = tab.substring(2);
//Fade out the navigation submenu
for ( var i = 0; i <= numTab ; i++ ) {
var domElt = '#Et' + i + ' ul';
$(domElt).fadeOut(); // fadeIn will show the sub cat menu
}
}
);
As you see on the live version of it, it don't really works, all the tabs are fadein together, or seems to. How can i add a delay to get the "one-after-one fadein effect"?
Add dynamic delay like this -
$(domElt).delay(i*100).fadeOut();
Demo ---> http://jsfiddle.net/abJkD/2/
You can chain the fades:
function () {
var tab = this.id;
var numTab = +(tab.substring(2));
//Fade in the navigation submenu
var i = 0;
function doFade() {
if (i === numTab) return;
// In the fiddle provided, the element id values
// start at 1, not zero
var domElt = '#Et' + (i + 1) + ' ul';
i = i + 1;
$(domElt).fadeIn(300, doFade);
}
doFade();
},
(and similarly for the fade out)

replacing images inplace

I have a array of static images that I am using for an animation.
I have one frame image that I want to update the image of and I have seen a lot of tutorials on animating images with javascript just simply update the source of an image.
frame.src = animation[2].src; etc
When I look at the resource tracking in chrome, it doesnt look like they are getting cached even thought the web browser does download the image more than once but not once for each time it is displayed, so there is still some browser caching going on.
What is the best way to replace the frame image object with another image?
Well, you can either position all images absolute and give them a z-index, then use jQuery/JS to shuffle their z-indexes, bringing a new one to the top in a cross fader style,
or you can take all the id's and fadeone in slightly faster than the last one fades out.
Like so:
function fader(func) {
var currID = $('#mainimg ul').data('currLI');
var currLiStr = '#mainimg ul li#' + currID;
img = $(currLiStr).find('img').attr('src');
nextID = (currID == 'six') ? 'one' : $(currLiStr).next().attr('id');
nextLiStr = $('#mainimg ul li#' + nextID);
$(currLiStr).fadeOut(3000);
$(nextLiStr).fadeIn(2000).find('div.inner').delay(3000).fadeIn('slow').delay(6000).fadeOut('slow');
$('#mainimg ul').data('currLI',nextID);
}
Note 'six' is the id of the last li, reseting it back to one, but if you do $('#mainimg ul li:last').attr('id'); and $('#mainimg ul li:first').attr('id') to get the last and first id's, you can allow it to cope with any amount of images (obviously this is with li's given id's one, two and so on, but if you are finding out the last and first id you could use any structure.
Or you can set a ul width a width of all the li's multiplied, and give the li's the width of the images, and set overflow to hidden, then use JS to pull the li's left by the width of 1 li on each iteration in a slider like I have done here: http://www.reclaimedfloorboards.com/
There are loads of options
I ended up using jquery's replaceWith command and gave all the frames a class "frame" that i could select with $('.frame') which happened to only select visible frames.
<script type="text/javascript">
var animation = [];
var firstFrame = 1;
var lastFrame = 96;
var animationFrames = 16;
var loadedImageCount = 0;
$(function() {
$("button, input:submit",'#forecastForm').button();
$("#progressbar").progressbar({
value: 0
});
$('#id_Species').attr('onChange', 'loadAnimation($(\'#id_Species\').val(),$(\'#id_Layer\').val(),$(\'#id_StartTime\').val(),$(\'#id_EndTime\').val())' )
$('#id_Layer').attr('onChange', 'loadAnimation($(\'#id_Species\').val(),$(\'#id_Layer\').val(),$(\'#id_StartTime\').val(),$(\'#id_EndTime\').val())' )
$('#id_StartTime').attr('onChange', 'loadAnimation($(\'#id_Species\').val(),$(\'#id_Layer\').val(),$(\'#id_StartTime\').val(),$(\'#id_EndTime\').val())' )
$('#id_EndTime').attr('onChange', 'loadAnimation($(\'#id_Species\').val(),$(\'#id_Layer\').val(),$(\'#id_StartTime\').val(),$(\'#id_EndTime\').val())' )
});
if (document.images) { // Preloaded images
loadAnimation('Dry_GEM',1,1,96);
}
function rotate(animation, frame)
{
if (frame >= animation.length)
frame = 0;
$('.frame').replaceWith(animation[frame]);
window.setTimeout('rotate(animation,'+eval(frame+1)+')',150);
}
function loadAnimation(species, layer, startTime, endTime)
{
layer = Number(layer);
startTime = Number(startTime);
endTime = Number(endTime);
if (startTime > endTime)
{
swap = startTime;
startTime = endTime;
endTime = swap;
delete swap;
}
for (i=0;i<animation.length;i++)
delete animation[i];
delete animation;
animation = []
$('#progressbar').progressbar({value: 0});
loadedImgCount = 0;
animationFrames = endTime - startTime + 1;
for(i=0;i < animationFrames;i++)
{
animation[i] = new Image();
animation[i].height = 585;
animation[i].width = 780;
$(animation[i]).attr('class','frame');
animation[i].onload = function()
{
loadedImgCount += 1;
$('#progressbar').progressbar({value: eval(loadedImgCount / animationFrames * 100)});
};
animation[i].src = 'http://[[url]]/hemi_2d/' + species + '_' + layer + '_' + eval(i+startTime) + '.png';
}
}
</script>
The easiest way to do it is create a separate hidden image for each frame. Something like this:
var nextImage = (function(){
var imagePaths='basn0g01.png,basn0g02.png,basn0g04.png,basn0g08.png'.split(','),
imageHolder=document.getElementById('custom-header'),
i=imagePaths.length, imageIndex=i-1, img;
for (;i--;) {
img=document.createElement('img');
img.src='http://www.schaik.com/pngsuite/' + imagePaths[i];
if (i) img.style.display='none';
imageHolder.appendChild(img);
}
return function(){
imageHolder.childNodes[imageIndex].style.display='none';
if (++imageIndex >= imageHolder.childNodes.length) imageIndex=0;
imageHolder.childNodes[imageIndex].style.display='inline-block';
}
}());
Try this example on this page; paste it in the console and then call nextImage() a few times. Watch the top of the page.
edit
If you already have all the images in your HTML document, you can skip most of the above and just do something like this:
var nextImage = (function(){
var imageHolder=document.getElementById('custom-header'),
images=imageHolder.getElementsByTagName('img'),
i=images.length, imageIndex=0, img;
for (;i--;) if (i) images[0].style.display='none';
return function(){
imageHolder.childNodes[imageIndex].style.display='none';
if (++imageIndex >= imageHolder.childNodes.length) imageIndex=0;
imageHolder.childNodes[imageIndex].style.display='inline-block';
}
}());

Categories

Resources