Safari, Chrome runs code in window.load before page loaded - javascript

I have some html that looks like this:
<div class="nmMap-wrapper">
<div id="draggable" class="nmMap-image">
<div class="nmMap"></div>
</div>
</div>
and on the "nmMap" I have a background image set in the css.
I then have a javascript loading the background image, appdending it as a image, and then getting the width and height, and alerting all the diffirent variables.
The script looks like this:
jQuery(window).load(function($) {
sceneConstructor();
});
function sceneConstructor() {
var bgHeight;
var bgWidth;
var bgAspectRatio;
function init() {
getBgSize();
alertRatio();
}
function getBgSize() {
var bgsrc = jQuery('.nmMap').css('background-image')
.replace('url("', '')
.replace('url(', '')
.replace('")', '')
.replace(')', '')
.replace('"', '')
.replace("'", '');
var bgImg = jQuery('<img />');
//bgImg.hide();
jQuery('.nmMap').append(bgImg);
bgImg.attr('src', bgsrc);
bgImg.bind('load', function() {
var width = jQuery(this).width();
var height = jQuery(this).height();
alert('first height' + height);
setAspectRatio(width, height);
});
}
function setAspectRatio(width, height) {
alert('second height: ' + height);
bgHeight = height;
bgWidth = width;
bgAspectRatio = bgWidth / bgHeight;
alert('trejde: ' + bgHeight);
jQuery('.nmMap').addClass('ration');
}
function alertRatio() {
alert('bgheight ' + bgHeight);
alert('bgwidth ' + bgWidth);
alert('bgheight ' + bgHeight);
alert('bgaspect ' + bgAspectRatio);
}
init();
}
All this working in firefox, except that the first alert in alertRatio() always gets undefined. But in safari, chrome, and IE, it's like alertRaiom() is being run first, and because of that all the alerts are undefined.
Can someone help and tell me whats going on?

try the default .ready from jquery.
this code load after the dom is loaded.
jQuery( document ).ready(function() {
sceneConstructor();
}):
you can also
jQuery( window ).ready(function() {
sceneConstructor();
}):
source: https://api.jquery.com/ready/

Does it help if you bind() the event listener before you set the image's src attribute?

Related

Use jQuery zoom on background image

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>

Background image is not added through javascript

I am trying to use modernizr so I javascript can detect if the browser supports object-fit and object-position. The code I got from modernizr works fine, but if it detects something like no-object-fit I want to execute this bit of code:
if (!Modernizr.objectfit) {
$('.wrapper__figure').each(function() {
var $container = $(this),
imgUrl = $container.find('img').prop('src');
if (imgUrl) {
$container
.css('background-image', 'url(' + imgUrl + ')');
}
});
}
I don't seem to get this working. No changes are made inside of the browser if I check in developer mode(I am only testing this in IE. All the other browsers don't need this). I think that it has something to do with adding .css('background-image', 'url(' + imgUrl + ')'); to the $container, but I am not realy sure if this is the case or something else
Its attr not prop - because src is an attribute, not a property.
if (Modernizr.objectfit) {
$('.wrapper__figure').each(function() {
var $container = $(this),
imgUrl = $container.find('img').attr('src');
if (imgUrl) {
$container.css('background-image', 'url(' + imgUrl + ')');
}
});
}

When I remove an iframe and reopen it, the height is not calculated

I am using jQuery to
dynamically create an iframe,
hide the page content,
append the iframe to a hidden div,
calculate the height of the iframe,
set the hidden div to have a height which matches the height of the iframe,
show the hidden div ($("#products_container").slideDown()).
And this all works fine.
And then if you close that product, the iframe is removed and the original page contents come back. All is perfect!
And then if you open a second iframe, it has a height of 0. (This works fine in Chromium; but in Firefox, second and subsequent iframes always have a height of zero.)
The height of the iframe will depend on its content. They have quite simple HTML and reasonably complicated CSS, with min-heights and lots of padding.
I put sleep(5) at the top of the PHP code which generates the iframe, just to help me to double-check what’s going on. As expected, the console.log('URI: ' + uri) fires immediately, and console.log('src: ' + this.src); console.log('height: ' + infr_height) happens after the five-second delay. This means that the iframe is indeed loaded before we try to calculate the height.
I’ve tried using $(infr).load() instead of infr.onload. That makes no difference. I’ve made sure that the onload event is set before the src is set, and before the iframe is appended to the HTML, to ensure that it is fired correctly. I added $("iframe").remove() when the iframe is closed, to ensure that the previous iframe wasn’t hanging around confusing matters.
Nothing I can think of has any effect.
page_href = document.location.href;
function open_product(uri, hist) {
console.log('URI: ' + uri);console.log('URI: ' + uri);
$('p').slideUp();
$("#products_container").slideUp();
var infr = document.createElement('iframe');
infr.style.border = 'none';
var infr_height;
infr.onload = function() {
var $pc = $("#product_content");
$pc.css('width', '100%');
infr_height = $(this).contents().height();
console.log('src: ' + this.src);
console.log('height: ' + infr_height); // always zero on second and subsequent loads
$(this).css('width', '100%');
$(this).css('height', '100%');
$pc.height(infr_height);
$pc.slideDown();
if (hist) {
var uri = $(this).contents().find('#canonical').attr('href');
// I can't get the state to work the way I want it to, so I'll do this
// with the pathname. Bah!
history.pushState(null, null, uri);
}
var close = document.createElement('img');
close.src = '/custom/public/styles/gallery/fancybox/button_close.png';
close.onclick = close_product;
app.get("product_content").appendChild(close);
close.style.position = 'absolute';
close.style.right = '50px';
close.style.top = '10px';
};
infr.src = uri;
var pc = app.get("product_content");
pc.appendChild(infr);
pc.style.position = 'relative';
}
function show_all_prds() {
var $pc = $("#product_content")
$pc.slideUp();
$("iframe").remove();
$pc.empty();
$pc.attr('style', '');
$('p').slideDown();
$("#products_container").slideDown();
}
function close_product() {
show_all_prds();
history.pushState(null, null, page_href);
}
$("a.inlineframe").click(function(e) {
e.preventDefault();
open_product(this.href, true);
});
window.onpopstate = function(e) {
var uri = document.location.toString().split('/');
var section = uri[3];
if (section === 'products') {
var prd = uri[4];
console.log(prd);
var open = '/custom/api/product.output.php?name=' + prd;
open_product(open, false);
} else {
show_all_prds();
}
};

I want to assign width of div with document.ready() but unable to do so?

Trying this code , but not working :
$(document).onload(function () {
var wid = $(window).width();
var hdsize = wid / 16 + " em";
$("#hd").css("width", hdsize);
});
Instead it loads pre-fed values.
Should be:
$(window).load(function () {...});
document doesn't fire onload, which in jQuery is load, hence window instead document.
If you need only to wait until document has been parsed, you can use:
$(document).ready(function () {...});
And as Hugo has stated in his comment, you need to remove the space from the unit:
var hdsize = wid / 16 + "em";.
$(document).ready(function(){
var wid = $(window).width();
var hdsize = wid / 16;
$("#hd").css("width", hdsize +" em");
});

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.

Categories

Resources