Use jQuery zoom on background image - javascript

I'd like to use the jQuery zoom on background images. The problem is, it works on images with img tags only. Is there any way to use it on background-images aswell?
I can't use img tag, because this value comes from javascript.
For example, I have this div:
<div class="main-image" style="background-image: url("image.jpg");"></div>
$(document).ready(function() {
$('.main-image').zoom();
});
(function() {
let gallerys = document.querySelectorAll('.gallery');
gallerys.forEach(gallery => {
updateGalleryPictures(gallery);
});
})();
function updateGalleryPictures(gallery) {
// Get gallery's thumbnail images
let thumbnails = gallery.querySelectorAll('.thumbnail');
// Change the background-image property on click
thumbnails.forEach(thumbnail => {
thumbnail.addEventListener('click', () => {
updateMainImage(gallery, thumbnail.src)
});
});
// Initialize background-image property using the 1st thumbnail image
let firstThumbnail = thumbnails[0];
if (firstThumbnail === null || firstThumbnail === undefined) return;
updateMainImage(gallery, firstThumbnail.src)
}
function updateMainImage(gallery, src) {
// Get main image and check if it exists
let mainImage = gallery.querySelector('.main-image');
if (mainImage === null) return;
mainImage.style.backgroundImage = 'url(' + src + ')';
}

The following is the source code of the plugin in question. https://github.com/jackmoore/zoom/blob/master/jquery.zoom.js - it is not designed to work on background images as you can see from lines https://github.com/jackmoore/zoom/blob/master/jquery.zoom.js#L117 and https://github.com/jackmoore/zoom/blob/master/jquery.zoom.js#L231 two properties which aren't available on divs.
You may get some mileage using pure CSS moving on mousemove something like:
$('.main-image').mousemove(function(e){
var amountMovedX = (e.pageX * -1 / 2);
var amountMovedY = (e.pageY * -1 / 2);
$(this).css({
'background-size': '200%',
'background-position': amountMovedX + 'px ' + amountMovedY + 'px'}
);
});
.main-image {
background-image:url('https://www.travelandleisure.com/sites/default/files/styles/tnl_redesign_article_landing_page/public/1453920892/DUBAI-554088081-ABOVE0116.jpg?itok=dcoZnCrc');
background-size: 100%;
display:block;
height:200px;
width:200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main-image">
</div>

Related

Change background url of div via HTML tag

I have a div (CSS - height: 250px, width: 70%) and I have set a background via CSS. I want to change the background onhover.
That's simple, I know. But I want to get sources of backgrounds from the HTML tag.
Ex.:
<div class="somediv" data-imgbefore="img1.png" data-imgafter="img2.png"></div>
Can anyone help me please?
If you're not using jQuery you can achieve the desired effect using basic Event Listeners. https://jsfiddle.net/gnu9utos/3/
// first get the element that we'll be interacting with
var element = document.querySelector('.somediv');
// assuming we managed to successfully get the element from the document
if(element) {
var before = element.getAttribute('data-imgbefore');
var after = element.getAttribute('data-imgafter');
if(before && after) {
element.style.background = 'url(' + before + ')'; // set the initital state
element.addEventListener('mouseover', function(event) {
element.style.background = 'url(' + after + ')';
});
element.addEventListener('mouseout', function(event) {
element.style.background = 'url(' + before + ')';
});
}
}
You might want to add a check for mouseleave to revert the image back to it's original state and add a little bit of css.
I hope this was helpful.
you can do this with this simple JQ
maybe it's not the best solution but it works.i added background-color so you can see the change. but you can remove that and leave only background-image
see here
jsfiddle
made 2 variables and assigned them to each image ( before and after img ) to each div with class .somediv
add an initial background-image to the div
then at hover, the background-image of the div changes between imgbefore and imgafter
jq :
$(".somediv").each(function(){
var imgbef = $(this).data("imgbefore"),
imgaft = $(this).data("imgafter")
$(this).css({'background-image': 'url(' + imgbef + ')','background-color':'red'});
$(this).hover(function(){
$(this).css({'background-image': 'url(' + imgaft + ') ','background-color':'blue'});
}, function(){
$(this).css({'background-image': 'url(' + imgbef + ')','background-color':'red'});
});
});
HTML :
<div class="somediv" data-imgbefore="img1.png" data-imgafter="img2.png"></div>
CSS :
.somediv {
height:250px;
width:70%;
}
let me know if it helps
You can easily achieve that with javascript. You can also add an onmouseleave function, but this time, passing this.dataset.imgbefore as second argument.
changebg = function(el, i) {
var t = "url("+i+")";
el.style.backgroundImage = t;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="somediv" id="mydiv" data-imgbefore="http://lorempixel.com/400/200/sports" data-imgafter="http://lorempixel.com/400/200/animals" onmouseover="changebg(this, this.dataset.imgafter)">Lorem</div>
</body>
</html>
You can add all the div that you like and change only the data-imgbefore and data-imgafter !!!
$(document).ready(function(){
$('.somediv').each(function( index, value ) {
var img = $(this).attr('data-imgbefore');
$('.somediv').css({'background-image':'url('+ img +')', 'background-size':'200px 200px'});
});
//$('.somedive').css({'background-image':'url("http://www.palladio-tv.it/Internet/siti_gec/2B/Manzan_Disney/codice/Pippo.png")', 'background-size':'200px 200px'});
$('.somediv').hover(
function () {
var img = $(this).attr('data-imgafter');
$(this).css({'background-image':'url('+ img +')', 'background-size':'200px 200px'});
},
function () {
var img = $(this).attr('data-imgbefore');
$(this).css({'background-image':'url('+ img +')', 'background-size':'200px 200px'});
}
);
});
.somediv {width:200px;height:200px;border:1px solid #F2F2F2;border-radius:4px;display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="somediv" data-imgbefore="http://www.palladio-tv.it/Internet/siti_gec/2B/Manzan_Disney/codice/Pippo.png" data-imgafter="http://www.filastrocche.it/contenuti/wp-content/uploads/2001/04/pippogoofy_352.jpg"></div>
<div class="somediv" data-imgbefore="http://www.palladio-tv.it/Internet/siti_gec/2B/Manzan_Disney/codice/Pippo.png" data-imgafter="http://www.filastrocche.it/contenuti/wp-content/uploads/2001/04/pippogoofy_352.jpg"></div>
Cheers!!!
Not sure if I understand what you are trying to accomplish. Why don't you abandon the HTML tag requirement and just try css :hover?
#somediv {
background: url(...);
}
#somediv:hover {
background: url(...); /* different url */
}
http://www.w3schools.com/cssref/css3_pr_background.asp

How to refresh offsetHeight of div after changing img src on child using pure javascript?

I need to change an image in a div and then immediately centre it on the screen by calculating its height and width and then setting its left and top values. But when I change the img src and then try to get the div's offsetHeight and clientHeight, both the values are wrong. Strangely the offsetWidth and clientWidth values are correct.
Is there a way to refresh the div and get the correct value?
Edit: It appears that changing the image src makes everything after that not work. The change to the onclick event imageObj.onclick = function() {contractImageView(imageId);}; isn't working now either. If I comment out the if statement it all starts working again.
Below is the code...
// Get the page dimensions
var pageBody = document.getElementById(currentBody);
// If you couldn't get the page body, abort.
if (!pageBody) {
return;
}
var pageBodyHeight = window.innerHeight;
var pageBodyWidth = pageBody.offsetWidth;
var imageDiv = document.getElementById(imageId);
var imageObj = imageDiv.children[0];
var paraObj = imageDiv.children[1];
// If you can't get the div or its image, then abort.
if (!imageDiv || !imageObj) {
return;
}
// Check whether the image has been loaded yet, and load if needed
if (imageObj.src.indexOf('lazy_placeholder.gif') !== -1) {
for (item in photoLazyData) {
if (item === imageDiv.parentElement.id) {
imageObj.src = photoLazyData[item][imageDiv.id];
}
}
}
// Change the images class.
imageDiv.className = 'active_design_div';
imageDiv.style.visibility = 'visible';
imageDiv.style.opacity = 1;
// Set the objects new onclick method to collapse the image
imageObj.onclick = function() {contractImageView(imageId);};
// Calculate the right size
imageDiv.style.maxHeight = pageBodyHeight + 'px';
imageDiv.style.maxWidth = pageBodyWidth + 'px';
imageObj.style.maxHeight = pageBodyHeight + 'px';
imageObj.style.maxWidth = pageBodyWidth + 'px';
// Calculate the margins.
var imageDivWidth = imageDiv.offsetWidth || imageDiv.clientWidth;
// ## THIS IS WRONG IF THE ABOVE IF STATEMENT CHANGES THE SRC ##
var imageDivHeight = imageDiv.offsetHeight || imageDiv.clientHeight;
console.log(imageDiv.offsetHeight + ' : ' + imageDiv.clientHeight);
console.log(imageDiv.offsetWidth + ' : ' + imageDiv.clientWidth);
var leftOffset = (pageBodyWidth - imageDivWidth) / 2;
var topOffset = (pageBodyHeight - imageDivHeight) /2;
// Adjust styling to make the div visible and centred.
imageDiv.style.left = String(leftOffset) + 'px';
imageDiv.style.top = String(topOffset) + 'px';
currentId = imageId;
toggleBlackDiv();
Edit: I got this working in the end using Joonas89's answer. I basically moved the if statement that changes the src value to another function that is called prior to the one above. This solved the onclick problem mentioned above. I then changed the divs left/top from calculated values to 50% as detailed by Joonas89 (but on the container div rather than the img element), along with the new transform property. The div and img already had a position value of fixed so didn't need to change that.
Are you sure u want to calculate top and left positions? Wouldent it be better to add a class like this, that always centers it
.parentDiv{
position: relative;
}
.imageElement{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

Canvas implementation on different images

i'm using next sample in my code: http://jsfiddle.net/8wegxnz3/
var lasticon;
$(function () {
$('.icon').click(function () {
if (lasticon != this.id) {
$('#' + lasticon + 'L').toggle();
lasticon = this.id;
} else {
lasticon = null;
}
$('#' + this.id + 'L').toggle();
});
});
.iconL {
display: none;
margin-top: 70px;
margin-left: 100px;
height: 100px;
width: 100px;
position: absolute;
}
var lasticon;
$(function () {
$('.icon').click(function () {
if (lasticon != this.id) {
$('#' + lasticon + 'L').toggle();
lasticon = this.id;
} else {
lasticon = null;
}
$('#' + this.id + 'L').toggle();
});
});
What I want is to implement the next solution to my first code I found in the next jfiddle: http://jsfiddle.net/m1erickson/LAS8L/
I have make some test and tried to implement it to my code, but nothing happens.
I would like to be able to resize and move the second image that appear when clicking the first image. So you could for example click the "e-mail icon" and then resize the second icon that appears.
This is not really easy. But here are some starting points:
read this tutorial about image cropping and resizing with canvas
see my jsBIN as an example implementation. You can copy the code, add an image to the <img class="resize-image" src="img/YOURIMAGE.jpg" alt="image for resizing"> tag and you can resize and crop it
alternative you can use this jquery plugin
Basically you doing the following:
load the original image into the DOM
Resize and crop your image with Javascript to display the cropping result to your user.
load the original image into a canvas
crop & resize the image in the canvas with the data returned by the user (Step 2)
extract the image with the toDataURL function from the canvas
Send the DataURL to a web service that saves this information to your webs erver hard disk.

Getting dimensions of background-image

I'm trying to get width and height of element's background-image. When you click on it, it should show it inside the element ("200 300" in this case).
HTML:
<div id='test'></div>
CSS:
#test {
width: 100px; height: 100px;
background-image: url(http://placehold.it/200x300);
}
JavaScript:
$('#test').on('click', function () {
$(this).text(getDimensions($(this)));
});
var getDimensions = function(item) {
var img = new Image(); //Create new image
img.src = item.css('background-image').replace(/url\(|\)$/ig, ''); //Source = clicked element background-image
return img.width + ' ' + img.height; //Return dimensions
};
Here's the Fiddle. The problem is it works only in Chrome, all the other main browsers return "0 0". I have no idea what's the reason. Isn't that graphic fully loaded?
The issue is that some browsers add quotes to the CSS, and it was trying to load (in the fiddle's case) "http://fiddle.jshell.net/_display/%22http://placehold.it/200x300%22". I've updated your .replace() to look for " as well, and a fiddle is at http://jsfiddle.net/4uMEq/
$('#test').on('click', function () {
$(this).text(getDimensions($(this)));
});
var getDimensions = function (item) {
var img = new Image();
img.src = item.css('background-image').replace(/url\(|\)$|"/ig, '');
return img.width + ' ' + img.height;
};
I guess you need to wait for onload event on image.

How to change Fancybox preloader image?

I want replace default Fancybox1.3.4 image preloader (fancy_loading.png) with another preloader.
The Fancybox preloader coded not only in css, but also in javascript itself.
Seems, there are two places in javascript, at least:
_animate_loading = function() {
if (!loading.is(':visible')){
clearInterval(loadingTimer);
return;
}
$('div', loading).css('top', (loadingFrame * -40) + 'px');
loadingFrame = (loadingFrame + 1) % 12;
};
and
$.fancybox.showActivity = function() {
clearInterval(loadingTimer);
loading.show();
loadingTimer = setInterval(_animate_loading, 66);
};
$.fancybox.hideActivity = function() {
loading.hide();
};
So customizing the preloader will require modifying javascript too.
How can I change fancybox-1.3.4 javascript to set custom preloader image?
The CSS declaration is here:
#fancybox-loading div {
position: absolute;
top: 0;
left: 0;
width: 40px;
height: 480px;
background-image: url('fancybox.png');
}
They are using a sprite for the background image and changing the background-position to animate it. If you're going to use a loading.gif image, then you won't need to animate it.
You need to change the background-image path, height, and width to cater to your new image. You may want to comment out their JS code for the animation so that it doesn't conflict.
The loading div is being declared here:
$('body').append(
tmp = $('<div id="fancybox-tmp"></div>'),
loading = $('<div id="fancybox-loading"><div></div></div>'),
overlay = $('<div id="fancybox-overlay"></div>'),
wrap = $('<div id="fancybox-wrap"></div>')
);
You can either piggyback on the loading variable or simply change the styling on #fancybox-loading. You'll then need to remove any reference to loadingTimer and loadingFrame. Comment out this entire function:
/*_animate_loading = function() {
if (!loading.is(':visible')){
clearInterval(loadingTimer);
return;
}
$('div', loading).css('top', (loadingFrame * -40) + 'px');
loadingFrame = (loadingFrame + 1) % 12;
};*/
Modify the following function:
$.fancybox.showActivity = function() {
//clearInterval(loadingTimer);
loading.show();
//loadingTimer = setInterval(_animate_loading, 66);
};
That should do it. You don't want loading to have any setInterval on it since you won't be animating it, but you do want it to hide/show conditionally.
There are two options -
1) Upgrade to v2 as it is now using animated gif
2) Ĺ–eplace showActivity and hideActivity methods with yours, e.g., after including js file -
$.fancybox.showActivity = function() {
/* Add your animated gif to page ... */
}
You dont need to change so much just in js file comment some lines:
$.fancybox.showActivity = function() {
//clearInterval(loadingTimer);
loading.show();
//loadingTimer = setInterval(_animate_loading, 66);
};
Thats all and it will work, but remember change in correct file because where are jquery.fancybox-1.3.4.js and jquery.fancybox-1.3.4.pack.js

Categories

Resources