JS: Set animation duration for change of src - javascript

I'm using this script for change img on click function
var fstSrc = 'img/1.jpg';
var sndSrc = 'img/2.jpg';
var trdSrc = 'img/3.jpg';
$(".aktualita1").click(function () {
$('img[src="' + sndSrc + '"]').attr('src', fstSrc);
$('img[src="' + trdSrc + '"]').attr('src', fstSrc);
});
When click, image changes immidiately, of course. How could i set a 0.5s duration for this click, so images will change with nice fade animation? :) Thanks!

You can fadeOut change the src of the image and then fadeIn giving you the desired effect.
var fstSrc = 'img/1.jpg';
var sndSrc = 'img/2.jpg';
var trdSrc = 'img/3.jpg';
$(".aktualita1").click(function () {
$('img[src="' + sndSrc + '"], img[src="' + trdSrc + '"]').fadeOut(250, function(){
$(this).attr('src', fstSrc);
}).fadeIn(250)
});
If you want the image to fade on top of the other one, consider using another image element on top of that one (or viceversa).
For example:
var fstSrc = 'https://i.imgur.com/EUym7Pw.jpg';
var sndSrc = 'https://i.imgur.com/Xt8ICog.jpg';
var trdSrc = 'https://i.imgur.com/Fp2EwFc.jpg';
$(".aktualita1").click(function() {
$('img[src="' + sndSrc + '"], img[src="' + trdSrc + '"]').each(function() {
if ($(this).is(':visible')) {
var pos = $(this).position();
$(this).parent().append($('<img src="' + fstSrc + '">').css({
position: 'absolute',
left: pos.left,
top: pos.top,
display: 'none'
}).fadeIn(500));
$(this).fadeOut(500);
}
})
});
.aktualita1 {
position: relative;
}
.aktualita1 img {
height: 200px;
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="aktualita1">
<img src="https://i.imgur.com/Xt8ICog.jpg">
<img src="https://i.imgur.com/Fp2EwFc.jpg">
</div>

Related

Popover position in div with position absolute

I have a problem with popover position.
This is what it looks like:
This is what it is supposed to look like:
With position: relative; on the timetable, the popover works, but the timetable doesn't:
Code:
In my html file I have one div with position: relative;
<div id="bg-timetable" class="bg-timetable"/>
In my JS, I create in it a small div with timetable with that has position: absolute;. For event I have a function:
function createDivEvent(event) {
var start = new Time(event.startTime);
var end = new Time(event.endTime);
var div = document.createElement("div");
div.classList.add("event");
div.id = event.id;
div.style.top = start.getPercent() + "%";
div.style.height = (end.getPercent() - start.getPercent()) + "%";
div.innerHTML = event.subject.name + " (" + event.place.name + ")";
var a = document.createElement('a');
a.setAttribute('tabindex', "0");
a.setAttribute('data-toggle','popover');
a.setAttribute('data-content','Some content inside the popover');
a.setAttribute('title',div.innerHTML);
a.appendChild(div);
var d = new Date(event.date)
document.getElementById(weekday[d.getDay()]).appendChild(a);
}
Can You help me?
Ok I fix it:
function createDivEvent(event) {
var start = new Time(event.startTime);
var end = new Time(event.endTime);
var div = document.createElement("div");
div.id = event.id;
div.innerHTML = event.subject.name + " (" + event.place.name + ")";
var a = document.createElement('a');
a.setAttribute('tabindex', "0");
a.setAttribute('data-toggle','popover');
a.setAttribute('data-content','Some content inside the popover');
a.setAttribute('title',div.innerHTML);
a.setAttribute('data-placement',"top");
a.appendChild(div);
a.style.top = start.getPercent() + "%";
a.style.height = (end.getPercent() - start.getPercent()) + "%";
a.classList.add("event");
var d = new Date(event.date)
document.getElementById(weekday[d.getDay()]).appendChild(a);
}
Css:
a.event {
position: absolute;
width: 95%;
background-color: lightblue;
}

Change Background image url of div

i have a div for which i want to show multiple images in the background as a fade in fade out by changing the css background image am unable to find the best way.
JSFiddle
My HTML:
<div id="background"></div>
Jquery
var bgArr = ["http://malsup.github.io/images/p1.jpg", "http://malsup.github.io/images/p1.jpg", "images/TopImage-03.jpg"];
var i = 0;
// Start the slide show
var interval = self.setInterval("swapBkgnd()", 5000)
function swapBkgnd() {
if (i > (bgArr.length - 1)) {
i = 0
$("#background").css("background-image", "url(" + bgArr[i] + ")");
} else {
$("#background").css("background-image", "url(" + bgArr[i] + ")");
}
i++;
};
CSS:
#background {
position: absolute;
min-height: 100%;
width: 100%;
height: auto;
top: 0;
left: 0;
background: url(http://2.bp.blogspot.com/-ayEwJpMGTPQ/USqliwPWo1I/AAAAAAAAHtI/ab6NHVy0Q48/s1600/tree.jpg) no-repeat center center;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Use:
Jsfiddle: http://jsfiddle.net/ook3ah4p/
var interval = self.setInterval(swapBkgnd, 5000) // true syntax
instead of:
var interval = self.setInterval("swapBkgnd()", 5000) // wrong syntax
for animation:
$('#background')
.animate({opacity: 0}, 'slow', function() {
$(this)
.css({'background-image': "url(" + bgArr[i] + ")"})
.animate({opacity: 1});
});
Set it up like this:
function swapBkgnd() {
if (i > (bgArr.length - 1)) {
i = 0;
}
$("#background").fadeOut("slow", function () {
$(this).css("background-image", "url(" + bgArr[i] + ")");
$(this).fadeIn("slow");
});
i++;
};
Refering to this answer How to fade changing background image
var interval = self.setInterval(swapBkgnd, 5000)
function swapBkgnd() {
if (i > (bgArr.length - 1)) {
i = 0
$('#background').fadeTo('slow', 0.3, function(){
$(this).css('background-image', 'url(' + bgArr[i] + ')');
}).fadeTo('slow', 1);
} else {
$('#background').fadeTo('slow', 0.3, function(){
$(this).css('background-image', 'url(' + bgArr[i] + ')');
}).fadeTo('slow', 1);
}
i++;
};

Overlay button over all images

Basically i want to loop through the html and get all the pictures and overlay a small button on them on hover, so when the user is clicking on that button, a bunch of info about that picture will appear. Right now i can overlay a small icon over a photo that will generate a popup when it's clicked, but i don't know how to dynamically add a icon on all photos on hover. This is what i've done so far http://jsfiddle.net/s5sp1h6e/1/
//Getting all the images
function getAllImages()
{
var images = document.getElementsByTagName('img');
var srcList = [];
for(var i = 0; i < images.length; i++)
{
srcList.push(images[i].src);
}
}
I've found a script that overlays a image over all images but every time i'm changing the size of the image i'm overlaying, the script stops working and i can't understand why.
If i want to change in this line the width and the height to be given hardcoded, the script stops working.
var overlay = $('<img class="protectionOverlay" src="' + overlayImg + '" width="' + img.width() + '" height="' + img.height() + '"/>') bla bla..
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function()
{
var overlayImg = 'http://www.privdog.com/PrivDog/logo-medium.png';
var useOnAllImages = true;
// Preload the pixel
var preload = new Image();
preload.src = overlayImg;
$('img').on('mouseenter touchstart', function(e)
{
// Only execute if this is not an overlay or skipped
var img = $(this);
if (img.hasClass('protectionOverlay')) return;
if (!useOnAllImages && !img.hasClass('protectMe')) return; // The script will be applied to all images. IF u don't want this -> useOnAllImages = false and class="protectMe"
// Get the real image's position, add an overlay
var pos = img.offset();
//var xx = overlayImg.offset();
//alert(xx.top);
var overlay = $('<img class="protectionOverlay" src="' + overlayImg + '" width="' + img.width() + '" height="' + img.height() + '"/>').css({position: 'absolute', zIndex: 9999999, left: pos.left, top: pos.top}).appendTo('body').bind('mouseleave', function()
{
setTimeout(function(){ overlay.remove(); }, 0, $(this));
});
if ('ontouchstart' in window) $(document).one('touchend', function(){ setTimeout(function(){ overlay.remove(); }, 0, overlay); });
});
}
Basically you need to add a an event handler for mouseover and mouseout. In the handler apply the necessary changes to the image.
$("img").on("mouseover", function () {
$(this).addClass("overlay-class");
var icon = $("<span class='icon' />").appendTo(document.body);
// logic to position the icon
}).on("mouseout", function () {
$(this).removeClass("overlay-class");
$(".icon").remove();
});

Setting the height & width of a div's background image, without knowing them in advance

using jQuery:
Whenever someone adds a background image to a div, the width and height of the background image need to be known in advance.
e.g.
$("#id-of-some-div").css(
{
backgroundImage: 'url(' + backgroundImageUrl + ')',
height: 200,
width: 450,
position: 'absolute',
top: 20,
left: 20
});
Could I get the size of the image simply by using code as follows :
I've tested the following but it's not working, is it because I cannot use a return statement inside a $.load function? -I'm guessing a return statement needs to always be synchronous right?
e.g.
var bgImageUrl = "/*insert image url*/";
var backgroundImageHeightAndWidth = function(backgroundImageUrl)
{
var backgroundImageSize = [];
var backgroundImage = new Image();
backgroundImage.src = backgroundImageUrl;
backgroundImage.id = "background-image-id";
$("#background-image-id").load(function ()
{
backgroundImageSize.push($("#background-image-id").height());
backgroundImageSize.push($("#background-image-id").width());
return backgroundImageSize;
});
};
var backgroundImageHeightAndWidthArray = backgroundImageHeightAndWidth();
var backgroundImageHeight = backgroundImageHeightAndWidthArray[0];
var backgroundImageWidth = backgroundImageHeightAndWidthArray[1];
$("#id-of-some-div").css(
{
backgroundImage: 'url(' + backgroundImageUrl + ')',
height: backgroundImageHeight,
width: backgroundImageWidth,
position: 'absolute',
top: 20,
left: 20
});
var bg = "/*insert image url*/";
var bgimg = new Image();
bgimg.onload = function() {
var elem = document.getElementById('id_of_element');
elem.style.backgroundImage = 'url(' + bg + ')';
elem.style.height = this.height + 'px';
elem.style.width = this.width + 'px';
elem.style.position = 'absolute',
elem.style.top = '20px';
elem.style.left = '20px';
});
bgimg.src = bg;

Loading and position image, when the another images are loaded

I have a small problem with loading and position one of my images. The smallest one. I'm using spacegallery script (http://www.eyecon.ro/spacegallery/).
It's loading good, but i want it to position it in the corner of bigger image, and when i load my page for the first time, it's not positioned, when i reload it - it's all fine, but the first loading is wrong.
Here are the screens:
It's the first load without refreshing the site:
first load http://derivativeofln.com/withoutload.png
Second and next loads:
second load http://derivativeofln.com/withload.png
My HTML:
<div id="myGallery" class="spacegallery">
<img class="imaz" src=http://derivativeofln.com/magnifier.jpg />
<img class="aaa" src=images/bw1.jpg alt="" atr1="bw1" />
<img class="aaa" src=images/bw2.jpg alt="" atr1="bw2" />
<img class="aaa" src=images/bw3.jpg alt="" atr1="bw3" />
</div>
MY CSS:
#myGallery0 {
width: 100%;
height: 300px;
}
#myGallery0 img {
border: 2px solid #52697E;
}
a.loading {
background: #fff url(../images/ajax_small.gif) no-repeat center;
}
.imaz {
z-index: 10000;
}
.imaz img{
position: absolute;
left:10px;
top:10px;
z-index: 10000;
width: 35px;
height: 35px;
}
My Jquery main script file: (the first positioning instructions are on the bottom, so feel free to scroll down : ))
(function($){
EYE.extend({
spacegallery: {
animated: false,
//position images
positionImages: function(el) {
var top = 0;
EYE.spacegallery.animated = false;
$(el)
.find('a')
.removeClass(el.spacegalleryCfg.loadingClass)
.end()
.find('img.aaa')
.removeAttr('height')
.each(function(nr){
var newWidth = this.spacegallery.origWidth - (this.spacegallery.origWidth - this.spacegallery.origWidth * el.spacegalleryCfg.minScale) * el.spacegalleryCfg.asins[nr];
$(this)
.css({
top: el.spacegalleryCfg.tops[nr] + 'px',
marginLeft: - parseInt((newWidth + el.spacegalleryCfg.border)/2, 10) + 'px',
opacity: 1 - el.spacegalleryCfg.asins[nr]
})
.attr('width', parseInt(newWidth));
this.spacegallery.next = el.spacegalleryCfg.asins[nr+1];
this.spacegallery.nextTop = el.spacegalleryCfg.tops[nr+1] - el.spacegalleryCfg.tops[nr];
this.spacegallery.origTop = el.spacegalleryCfg.tops[nr];
this.spacegallery.opacity = 1 - el.spacegalleryCfg.asins[nr];
this.spacegallery.increment = el.spacegalleryCfg.asins[nr] - this.spacegallery.next;
this.spacegallery.current = el.spacegalleryCfg.asins[nr];
this.spacegallery.width = newWidth;
})
},
//constructor
init: function(opt) {
opt = $.extend({}, EYE.spacegallery.defaults, opt||{});
return this.each(function(){
var el = this;
if ($(el).is('.spacegallery')) {
$('')
.appendTo(this)
.addClass(opt.loadingClass)
.bind('click', EYE.spacegallery.next);
el.spacegalleryCfg = opt;
var listunia, images2 = [], index;
listunia = el.getElementsByTagName("img");
for (index = 1; index < listunia.length; ++index) {
images2.push(listunia[index]);
}
el.spacegalleryCfg.images = images2.length;
el.spacegalleryCfg.loaded = 0;
el.spacegalleryCfg.asin = Math.asin(1);
el.spacegalleryCfg.asins = {};
el.spacegalleryCfg.tops = {};
el.spacegalleryCfg.increment = parseInt(el.spacegalleryCfg.perspective/el.spacegalleryCfg.images, 10);
var top = 0;
$('img.aaa', el)
.each(function(nr){
var imgEl = new Image();
var elImg = this;
el.spacegalleryCfg.asins[nr] = 1 - Math.asin((nr+1)/el.spacegalleryCfg.images)/el.spacegalleryCfg.asin;
top += el.spacegalleryCfg.increment - el.spacegalleryCfg.increment * el.spacegalleryCfg.asins[nr];
el.spacegalleryCfg.tops[nr] = top;
elImg.spacegallery = {};
imgEl.src = this.src;
if (imgEl.complete) {
el.spacegalleryCfg.loaded ++;
elImg.spacegallery.origWidth = imgEl.width;
elImg.spacegallery.origHeight = imgEl.height
} else {
imgEl.onload = function() {
el.spacegalleryCfg.loaded ++;
elImg.spacegallery.origWidth = imgEl.width;
elImg.spacegallery.origHeight = imgEl.height
if (el.spacegalleryCfg.loaded == el.spacegalleryCfg.images) {
EYE.spacegallery.positionImages(el);
}
};
}
});
el.spacegalleryCfg.asins[el.spacegalleryCfg.images] = el.spacegalleryCfg.asins[el.spacegalleryCfg.images - 1] * 1.3;
el.spacegalleryCfg.tops[el.spacegalleryCfg.images] = el.spacegalleryCfg.tops[el.spacegalleryCfg.images - 1] * 1.3;
if (el.spacegalleryCfg.loaded == el.spacegalleryCfg.images) {
if(el.spacegalleryCfg.images == 3){
$('img.imaz', this).css('top', '27px'); // HERE IS POSITIONING OF MY IMAGES, WHEN SCRIPT LOADS FOR THE FIRST TIME!
$('img.imaz', this).css('left', (($(el).find('img.aaa:last').width())/2 + 77) + 'px' );
}
else if(el.spacegalleryCfg.images==2){
$('img.imaz', this).css('top', '33px');
$('img.imaz', this).css('left', (($(el).find('img.aaa:last').width())/2 + 77) + 'px' ); // HERE IT ENDS:)
}
EYE.spacegallery.positionImages(el);
}
}
});
}
}
});
})(jQuery);
this seems to be a cache thing
try to specify image dimensions (width and height) on your html, because on first load (images not in cache) the browser only knows dimensions after the load and the positioning might not be correct.
in alternative you can run your positioning code when the document is loaded
$(document).ready(«your poisitioning function here»)
see http://api.jquery.com/ready/ for that jquery ready function

Categories