I have a javascript function that resize and centers images based on the surrounding container size (that in turn depend on the window size). I use jquery as js framework. The function need to be executed after document load (on document ready) but also when and if the user changes size of the browser, ie I have the following running in the html-document:
$(document).ready(function(){
fixImageSizes();
});
$(window).resize(function() {
fixImageSizes();
});
But for some unknown reason the function is only executed when a user resizes the browser and not after loading. Can anyone please help with this?
(my function is below for knowledge...)
function fixImageSizes()
{
var cw = $('#imagecontainer').width();
var ch = $('#imagecontainer').height();
$('#imagecontainer img').each(function()
{
var iw = $(this).css('width');
var ih = $(this).css('height');
if (parseInt(iw) < parseInt(cw)) // image width < viewport
{
var newih = Math.ceil(parseInt(ih) * parseInt(cw) / parseInt(iw)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(newih)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(cw)/2) + 'px';
$(this).css({'width':cw,'height':newih,'margin-left':newimarginl,'margin-top':newimargint});
}
if (parseInt(ih) < parseInt(ch)) // image height < viewport
{
var newiw = Math.ceil(parseInt(iw) * parseInt(ch) / parseInt(ih)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(ch)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(newiw)/2) + 'px';
$(this).css({'width':newiw,'height':ch,'margin-left':newimarginl,'margin-top':newimargint});
}
if (parseInt(ih) > parseInt(ch) && parseInt(iw) > parseInt(cw)) // viewport smaller than image, shrink image
{
if (parseInt(ch) - parseInt(ih) > parseInt(cw) - parseInt(iw)) // difference is less on height
{
var newiw = Math.ceil(parseInt(iw) * parseInt(ch) / parseInt(ih)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(ch)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(newiw)/2) + 'px';
$(this).css({'width':newiw,'height':ch,'margin-left':newimarginl,'margin-top':newimargint});
}
else // difference less on width
{
var newih = Math.ceil(parseInt(ih) * parseInt(cw) / parseInt(iw)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(newih)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(cw)/2) + 'px';
$(this).css({'width':cw,'height':newih,'margin-left':newimarginl,'margin-top':newimargint});
}
}
});
You should use the load event instead of the ready event.
The ready event runs after the document has loaded, but before the images has loaded, so you won't have the correct size of all elements.
The function is probably executing (you can double-check with a simple alert), but the images you are "fixing" is probably not loaded yet. You can use the window.onload event or listen to the image load event like this:
var scale = function() {
// rescale
};
$('#imagecontainer img').each(function() {
this.complete ? scale.call(this) : $(this).load(scale);
});
Try this:
$(window).load(function (){
fixImageSizes();
});
Related
Ok I'm going to run this on the slowest ASP box I've ever seen before, so I'm not looking to use jQuery, I know it would make everything a lot easier but I need to keep my code as small as humanly possible. I'm targeting users with the slowest internet I've ever seen and loading the entire jQuery file will be to much for their internet to take. So I'm not looking to use jQuery for this script.
I'm trying to make a script that when the user hovers over the thumbnail the larger image pops up. I'm using the following javascript to achieve this:
var hoverImage = document.getElementById("largeImage");
function hoverZoom(selector) {
this.node = document.querySelector(selector);
if(this.node === null) {
console.log("Node not found");
}
return this.node.id;
}
hoverZoom.prototype.show = function(x, y) {
var largeImageSrc = this.node.name;
hoverImage.style.display = "block";
var largeWidth = hoverImage.offsetWidth;
var largeHeight = hoverImage.offsetHeight;
hoverImage.style.top = y - (largeHeight / 2) + "px";
hoverImage.style.left = x - (largeWidth / 2) + "px";
hoverImage.style.position = "absolute";
hoverImage.style.background = "url(" + largeImageSrc + ")";
}
hoverZoom.prototype.hide = function() {
hoverImage.style.display = "none";
}
hoverZoom.prototype.checkCoords = function(x, y) {
var id = document.getElementById(this.node.id);
var elemTop = id.offsetTop;
var elemLeft = id.offsetLeft;
var elemHeight = id.offsetHeight;
var elemWidth = id.offsetWidth;
console.log(x + " " + y + " " + this.node.id + " " + id + " " + elemHeight + " " + elemWidth + " " + elemTop + " " + elemLeft);
if(x >= elemLeft && x <= elemLeft + elemWidth && y >= elemTop && y <= elemTop + elemHeight) {
return true;
}
}
document.body.onmousemove = function(e) {
e = e || window.event;
while(hoverZoomPI.checkCoords(e.clientX, e.clientY) === true) {
var target = e.target || e.srcElement,
offsetX = e.clientX,
offsetY = e.clientY;
return hoverZoomPI.show(offsetX, offsetY);
}
hoverZoomPI.hide();
}
var hoverZoomPI = new hoverZoom(".test");
My problem is that when I hover over another image with the same class name nothing happens. But when I hover over the first image with the class name it works.
I've set up a jsFiddle with all my code and an example: http://jsfiddle.net/f7xqF/
Thanks everybody for their help. I can't say enough about how much you guys have helped me over the last few years.
You should use document.querySelectorAll instead document.querySelector to get an LIST of all nodes, not just first one. After that u should of course attach callbacks to all of collected elements.
I have a number of functions containing jquery that should be executed sequentially. They aren't used to create effects but rather to position certain elements at a calculated location inside a div. All online resources on jquery queue are focused on the creation of transitions or animations so it's hard to find a simple example on how to execute a number of simple functions sequentially.
I have these functions:
function bigItemRecalc(recalc, idBase, innerHeight, i) {
if (recalc < 0) {
$('#' + idBase + i).css('max-height', (innerHeight + (2 * recalc)));
recalc = 0;
}
return recalc;
}
function firstCheck(recalc, idBase, i) {
if (i == 1) {
$('#' + idBase + i).css('margin-top', recalc * -1);
}
}
function lastCheck(recalc, idBase, itemAmount, i) {
if (i == itemAmount) {
$('#' + idBase + i).css('margin-top', recalc);
}
}
function truncateItems(totalHeight, widgetHeight, idBase, i) {
if (totalHeight > (widgetHeight - 20)) {
$('#' + idBase + i).remove();
$('#' + idBase + "b" + i).remove();
}
}
In another function I want to execute these sequentially by using a jquery queue preferably , but I haven't got a clue how.
The code is called here:
function styleWidget(itemAmount, widgetHeight, widgetWidth, idBase) {
var innerHeight;
var outerHeight;
var recalc;
var totalHeight = 0;
var totalWidth = 0;
for (var i = 1; i <= itemAmount; i++)
{
if (widgetHeight >= widgetWidth)
{
totalHeight += $('#'+idBase+i).height();
innerHeight = $('#' + idBase + i).height();
outerHeight = (widgetHeight/itemAmount);
recalc = ((outerHeight / 2) - (innerHeight / 2));
recalc = bigItemRecalc(recalc, idBase, innerHeight, i);
$('#' + idBase + i).css('padding-top', recalc);
firstCheck(recalc, idBase, i);
lastCheck(recalc, idBase, itemAmount, i);
truncateItems(totalHeight, widgetHeight, idBase, i);
}
else
{
innerHeight = $('#'+idBase+i).height();
outerHeight = widgetHeight;
recalc = ((outerHeight/2)-(innerHeight/2));
$('#'+idBase+i).css('padding-top',recalc);
totalWidth += $('#'+idBase+i).width();
if (totalWidth > (widgetWidth-20))
{
$('#' + idBase + i).remove();
$('#' + idBase + "b" + i).remove();
}
}
}
}
The bottom part hasn't been updated just yet, but it can be ignored as it's being tested with portrait mode widgets.
I think I've found a clue. When no delay is introduced the values of totalHeight and innerHeight seem very low. So I assume that the page isn't fully loaded by the time the script is executed. Every time a new widget is generated the above script is called like this:
$(document).ready(styleWidget(3, 225, 169, 'id-871206010'));
This fixed it:Why does Firefox 5 ignore document.ready?
It seems like reloading the page did not trigger the .ready() function.
I'm currently trying to implement functionality similar to infinite/continuous/bottomless scrolling, but am coming up with my own approach (as an intern, my boss wants to see what I can come up with on my own). So far, I have divs of a fixed size that populate the page, and as the user scrolls, each div will be populated with an image. As of now, the function I've written works on the first div, but no longer works on successive divs.
$(window).scroll(function () {
var windowOffset = $(this).scrollTop();
var windowHeight = $(this).height();
var totalHeight = $(document).height();
var bottomOffset = $(window).scrollTop() + $(window).height();
var contentLoadTriggered = new Boolean();
var nextImageCount = parseInt($("#nextImageCount").attr("value"));
var totalCount = #ViewBag.totalCount;
var loadedPageIndex = parseInt($("#loadedPageIndex").attr("value"));
var calcScroll = totalHeight - windowOffset - windowHeight;
$("#message").html(calcScroll);
contentLoadTriggered = false;
if (bottomOffset >= ($(".patentPageNew[id='" + loadedPageIndex + "']").offset().top - 1000)
&& bottomOffset <= $(".patentPageNew[id='" + loadedPageIndex + "']").offset().top && contentLoadTriggered == false
&& loadedPageIndex == $(".patentPageNew").attr("id"))
{
contentLoadTriggered = true;
$("#message").html("Loading new images");
loadImages(loadedPageIndex, nextImageCount);
}
});
This is the image-loading function:
function loadImages(loadedPageIndex, nextImageCount) {
var index = loadedPageIndex;
for(var i = 0; i < nextImageCount; i++)
{
window.setTimeout(function () {
$(".patentPageNew[id='" + index + "']").html("<img src='/Patent/GetPatentImage/#Model.Id?pageIndex=" + index + "' />");
index++;
var setValue = index;
$("#loadedPageIndex").attr("value", setValue);
}, 2000);
}
}
I was wondering what may be causing the function to stop working after the first div, or if there might be a better approach to what I'm attempting?
EDIT: It seems that loadedPageIndex == $(".patentPageNew").attr("id") within the if statement was the culprit.
#ViewBag.totalCount; is not a JavaScript, it's .NET, so your script probably stops after encountering an error.
Also: ".patentPageNew[id='" + loadedPageIndex + "']" is inefficient. Since IDs must be unique, just query by ID instead of by class name then by ID.
I'm writing a rather complex AJAX driven menu with multiple levels that animate around allowing a user to navigate a complicated tree structure at some point I had to add a function that auto centers (vert and horz) the images associated with each item on the menu tree. In order to measure the images and position them accordingly I must first write them to a hidden div ("#tempHolder") once they .load() I can then get their dimensions, calculate my offsets and then write the images to the DOM in the appropriate place.
This all works A Okay in the standards compliant browsers but IE7-8 seem to only process the .load() command when they feel like it. (homepage the menu loads okay, first visit to a sub-page breaks the menu, refreshing said page fixes it again...etc.). I restructured my function to make the .load() declaration early because of the advice I read here (http://blog.stchur.com/2008/02/26/ie-quirk-with-onload-event-for-img-elements/) but that doesn't seem to have worked. I also added e.preventDefault because of a stackOverflow thread that said this might prevent IE from caching my load statements.
Here is the function causing the issues:
if (this.imagePath != "") {
runImage = function (imagePath, $itemEle) {
var $itemEleA = $itemEle.find('a');
var image = new Image();
//$thisImage = $(image);
$(image).load(function (e) {
//alert('image loaded')
$(image).evenIfHidden(function (element) {
//alert('even if hidden');
////////////console.log($thisImage);
var elementWidth = element.width();
var elementHeight = element.height();
this.imageHeight = elementHeight;
this.imageWidth = elementWidth;
//alert('widthoffset = ' + widthOffset + 'imagewidth = ' + imageWidth + 'this.imageWidth = ' + this.imageWidth + 'elementWidth = ' + elementWidth);
var imagePaddingWidth = 230 - imageWidth;
var widthOffset = imagePaddingWidth / 2;
widthOffset = widthOffset + "px";
element.css("left", widthOffset);
var imagePaddingHeight = 112 - imageHeight;
if (imagePaddingHeight < 0) {
var heightOffset = imagePaddingHeight;
heightOffset = heightOffset + "px";
element.css("top", heightOffset);
}
if (imagePaddingHeight > 0) {
var heightOffset = imagePaddingHeight - 18;
heightOffset = heightOffset + "px";
element.css("top", heightOffset);
}
});
$(this).appendTo($itemEleA);
e.preventDefault();
return image;
});
image.src = imagePath;
//var tempvar = $itemEle.find('a');
$(image).appendTo("#tempHolder");
}
this.image = runImage(this.imagePath, $itemEle);
}
Since this is for a big client and the site is not yet live I can't show the site but I'll try to throw up some screen shots later.
Any help is greatly appreciated.
It is quite a common problem, and if the images are already in the cache some browsers (shall I say directly - IE?) fails to trigger load events on them. Hence there is a technique for a workaround.
// After this line of your code
image.src = imagePath;
// put this
if (image.complete || image.naturalWidth > 0) { // if image already loaded
$(image).load(); // trigger event manually
}
How is it posible move an image from one position to other with fadeout?
I hav such functions
for hiding:
function SetOpacity(object,opacityPct)
{
// IE.
object.style.filter = 'alpha(opacity=' + opacityPct + ')';
// Old mozilla and firefox
object.style.MozOpacity = opacityPct/100;
// Everything else.
object.style.opacity = opacityPct/100;
}
function ChangeOpacity(id,msDuration,msStart,fromO,toO)
{
var element=document.getElementById(id);
var opacity = element.style.opacity * 100;
var msNow = (new Date()).getTime();
opacity = fromO + (toO - fromO) * (msNow - msStart) / msDuration;
if (opacity<0)
SetOpacity(element,0)
else if (opacity>100)
SetOpacity(element,100)
else
{
SetOpacity(element,opacity);
element.timer = window.setTimeout("ChangeOpacity('" + id + "'," + msDuration + "," + msStart + "," + fromO + "," + toO + ")",1);
}
}
function FadeOut(id)
{
var element=document.getElementById(id);
if (element.timer) window.clearTimeout(element.timer);
var startMS = (new Date()).getTime();
element.timer = window.setTimeout("ChangeOpacity('" + id + "',500," + startMS + ",100,0)",1);
}
for get current position or next position (by id of image and id of div)
function findPos(e){
var obj = document.getElementById(e);
var posX = obj.offsetLeft;var posY = obj.offsetTop;
while(obj.offsetParent){
posX=posX+obj.offsetParent.offsetLeft;
posY=posY+obj.offsetParent.offsetTop;
if(obj==document.getElementsByTagName('body')[0]){break}
else{obj=obj.offsetParent;}
}
alert(posX+'-'+posY);
}
the first position is position of image, and next - is position of div
The easiest approach with minimal code will be to use jQuery and use the animate function mate.
Ex:
$(".block").animate({"left": "+=50px"}, "slow");
You can use multiple parameters in the brackets like background-color, opacity, etc as you wish to dynamically change the values.
A link for your reference is located at: http://api.jquery.com/animate/
Most javascript animations rely on timer to create the effect of fluid motion. To slide an image across the page, you would set an interval that changed the css position to the right 1px every 5 milliseconds or something of the like. Javascript animation tutorial.
However, animation is most easily accomplished with a library like jquery or many others.