javascript working in firefox but not chrome - javascript

This code:
$('#ad img').each(function(){
if($(this).width() > 125){
$(this).height('auto');
$(this).width(125);
}
});
is working properly on Firefox but not Chrome. The img tags inside of #ad are constricted by height, but if this makes them too wide I need to restrain the width. Is there a better way to do this that would work on all browsers?
The html for the image is as follows:
<img src='http://easyuniv.com/img/ads/".$ad['img']."' height='40px'>

You could achieve this without javascript.
Use this in the css :
#ad img {
width: 125px;
height: auto;
overflow: hidden;
}

I suspect what is biting you is the variability in image load. If the image itself hasn't loaded by the time your code runs, it will have width of 0. You might want to try using a load handler as well as running your existing code to ensure that the images are sized properly. Note: you'll need to use your existing code to handle the case where the image is loaded before the load handler is added.
$(function() {
$('#ad img').on('load', function() {
resize(this);
}).each( function() {
resize(this);
});
function resize(image) {
var $image = $(image);
if ($image.width() > 125) {
$image.css( { height: 'auto', width: 125 } );
}
}
});

Try:
$(window).load(function () {
$('#ad img').each(function(){
if($(this).width() > 125){
$(this).height('auto');
$(this).width(125);
}
});
});

Did you try:
$('#ad img').each(function(){
if($(this).width() > 125) {
$(this).css('height', 'auto');
$(this).css('width',125);
}
})

Related

How to call a div height in jQuery and set it into the css of another div dynamically (upon window resizing)? [duplicate]

I have the following JQuery code:
$(document).ready(function () {
var $containerHeight = $(window).height();
if ($containerHeight <= 818) {
$('.footer').css({
position: 'static',
bottom: 'auto',
left: 'auto'
});
}
if ($containerHeight > 819) {
$('.footer').css({
position: 'absolute',
bottom: '3px',
left: '0px'
});
}
});
The only problem is that this only works when the browser first loads, I want containerHeight to also be checked when they are resizing the window?
Any ideas?
Here's an example using jQuery, javascript and css to handle resize events.
(css if your best bet if you're just stylizing things on resize (media queries))
http://jsfiddle.net/CoryDanielson/LAF4G/
css
.footer
{
/* default styles applied first */
}
#media screen and (min-height: 820px) /* height >= 820 px */
{
.footer {
position: absolute;
bottom: 3px;
left: 0px;
/* more styles */
}
}
javascript
window.onresize = function() {
if (window.innerHeight >= 820) { /* ... */ }
if (window.innerWidth <= 1280) { /* ... */ }
}
jQuery
$(window).on('resize', function(){
var win = $(this); //this = window
if (win.height() >= 820) { /* ... */ }
if (win.width() >= 1280) { /* ... */ }
});
How do I stop my resize code from executing so often!?
This is the first problem you'll notice when binding to resize. The resize code gets called a LOT when the user is resizing the browser manually, and can feel pretty janky.
To limit how often your resize code is called, you can use the debounce or throttle methods from the underscore & lodash libraries.
debounce will only execute your resize code X number of milliseconds after the LAST resize event. This is ideal when you only want to call your resize code once, after the user is done resizing the browser. It's good for updating graphs, charts and layouts that may be expensive to update every single resize event.
throttle will only execute your resize code every X number of milliseconds. It "throttles" how often the code is called. This isn't used as often with resize events, but it's worth being aware of.
If you don't have underscore or lodash, you can implement a similar solution yourself:
JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?
Move your javascript into a function and then bind that function to window resize.
$(document).ready(function () {
updateContainer();
$(window).resize(function() {
updateContainer();
});
});
function updateContainer() {
var $containerHeight = $(window).height();
if ($containerHeight <= 818) {
$('.footer').css({
position: 'static',
bottom: 'auto',
left: 'auto'
});
}
if ($containerHeight > 819) {
$('.footer').css({
position: 'absolute',
bottom: '3px',
left: '0px'
});
}
}
Try this solution. Only fires once the page loads and then during window resize at predefined resizeDelay.
$(document).ready(function()
{
var resizeDelay = 200;
var doResize = true;
var resizer = function () {
if (doResize) {
//your code that needs to be executed goes here
doResize = false;
}
};
var resizerInterval = setInterval(resizer, resizeDelay);
resizer();
$(window).resize(function() {
doResize = true;
});
});
jQuery has a resize event handler which you can attach to the window, .resize(). So, if you put $(window).resize(function(){/* YOUR CODE HERE */}) then your code will be run every time the window is resized.
So, what you want is to run the code after the first page load and whenever the window is resized. Therefore you should pull the code into its own function and run that function in both instances.
// This function positions the footer based on window size
function positionFooter(){
var $containerHeight = $(window).height();
if ($containerHeight <= 818) {
$('.footer').css({
position: 'static',
bottom: 'auto',
left: 'auto'
});
}
else {
$('.footer').css({
position: 'absolute',
bottom: '3px',
left: '0px'
});
}
}
$(document).ready(function () {
positionFooter();//run when page first loads
});
$(window).resize(function () {
positionFooter();//run on every window resize
});
See: Cross-browser window resize event - JavaScript / jQuery
Give your anonymous function a name, then:
$(window).on("resize", doResize);
http://api.jquery.com/category/events/
function myResizeFunction() {
...
}
$(function() {
$(window).resize(myResizeFunction).trigger('resize');
});
This will cause your resize handler to trigger on window resize and on document ready. Of course, you can attach your resize handler outside of the document ready handler if you want .trigger('resize') to run on page load instead.
UPDATE: Here's another option if you don't want to make use of any other third-party libraries.
This technique adds a specific class to your target element so you have the advantage of controlling the styling through CSS only (and avoiding inline styling).
It also ensures that the class is only added or removed when the actual threshold point is triggered and not on each and every resize. It will fire at one threshold point only: when the height changes from <= 818 to > 819 or vice versa and not multiple times within each region. It's not concerned with any change in width.
function myResizeFunction() {
var $window = $(this),
height = Math.ceil($window.height()),
previousHeight = $window.data('previousHeight');
if (height !== previousHeight) {
if (height < 819)
previousHeight >= 819 && $('.footer').removeClass('hgte819');
else if (!previousHeight || previousHeight < 819)
$('.footer').addClass('hgte819');
$window.data('previousHeight', height);
}
}
$(function() {
$(window).on('resize.optionalNamespace', myResizeFunction).triggerHandler('resize.optionalNamespace');
});
As an example, you might have the following as some of your CSS rules:
.footer {
bottom: auto;
left: auto;
position: static;
}
.footer.hgte819 {
bottom: 3px;
left: 0;
position: absolute;
}
Use this:
window.onresize = function(event) {
...
}
can use it too
function getWindowSize()
{
var fontSize = parseInt($("body").css("fontSize"), 10);
var h = ($(window).height() / fontSize).toFixed(4);
var w = ($(window).width() / fontSize).toFixed(4);
var size = {
"height": h
,"width": w
};
return size;
}
function startResizeObserver()
{
//---------------------
var colFunc = {
"f10" : function(){ alert(10); }
,"f50" : function(){ alert(50); }
,"f100" : function(){ alert(100); }
,"f500" : function(){ alert(500); }
,"f1000" : function(){ alert(1000);}
};
//---------------------
$(window).resize(function() {
var sz = getWindowSize();
if(sz.width > 10){colFunc['f10']();}
if(sz.width > 50){colFunc['f50']();}
if(sz.width > 100){colFunc['f100']();}
if(sz.width > 500){colFunc['f500']();}
if(sz.width > 1000){colFunc['f1000']();}
});
}
$(document).ready(function()
{
startResizeObserver();
});
You can bind resize using .resize() and run your code when the browser is resized. You need to also add an else condition to your if statement so that your css values toggle the old and the new, rather than just setting the new.

Removing An Appended jQuery Div When Window Resizes - jQuery

I've appended some divs onto a nav with jQuery. These are set so they append if the window is bigger than 980px.
I would like these appended divs to be removed if the window is less than 980px. The jQuery I'm using in the example works, but only if the window is this size when loaded. When I re-size the window the appended divs don't get removed or added which is what I need.
I have a codepen here: http://codepen.io/emilychews/pen/jBGGBB
The code is:
jQuery
if ($(window).width() >= 980) {
$('.box').append('<div id="newbox">appended with jQuery</div>');
}
if ($(window).width() <= 979) {
$('#newbox').remove();
}
CSS
.box{
position: relative;
left: 50px;
top: 50px;
height: 30px;
width: 100px;
background: blue;
line-height: 30px;
text-align: center;
color: white;
}
#newbox {
margin-top: 20px;
width: 100px;
height: 100px;
background: red;}
HTML
<div class="box">Test</div>
Any help would be wonderful.
Emily
I've updated your codepen to show how you can accomplish this:
Code Pen Here: http://codepen.io/anon/pen/ZeXrar
// Logic inside of function
function addRemoveDiv() {
// Window Width pointer
var wW = $(window).width();
// If window width is greater than or equal to 980 and div not created.
if (wW >= 980 && !$('#newbox').length) {
$('.box').append('<div id="newbox">appended with jQuery</div>');
// else if window is less than 980 and #newbox has been created.
} else if (wW < 980 && $('#newbox').length) {
$('#newbox').remove();
}
}
// Initial function call.
addRemoveDiv();
// On resize, call the function again
$(window).on('resize', function() {
addRemoveDiv();
})
Also, I would recommend looking into debouncing the function call on resize so it's not called over and over and over again as the window resizes. Reference for that here:
https://davidwalsh.name/javascript-debounce-function
Also, libraries like Underscore and LoDash have debounce functions available when sourced:
http://underscorejs.org/
https://lodash.com/
You should use event listeners.
$(document).ready(function() {
function checkMyDiv(calledByResize) {
if($(window).width() >= 980 && $('#newbox').length < 1) { // "$('#newbox').length < 1" will prevent to add lots of div#newbox elements
$('.box').append('<div id="newbox">appended with jQuery</div>');
} else if (calledByResize === true && $('#newbox').length > 0) {
$('#newbox').remove();
}
}
$(window).resize(function() {
checkMyDiv(true);
});
checkMyDiv(false);
});
You may also want to use css rules, like display:none|block; instead of removing or appending div#newbox element everytime the window resizes.
You're almost there, you just need the resize event, and for it to be applied after the ready event:
(function($) {
$(function() {
$(window).on('resize', function() {
if ($(window).width() >= 980) {
$('.box').append('<div id="newbox">appended with jQuery</div>');
}
if ($(window).width() <= 979) {
$('#newbox').remove();
}
}).trigger('resize');
});
})(jQuery);
Although, it should be noted this will actually append an additional copy of your newbox on every single resize event, which I'll assume you don't want. So, we'll sort out that problem.
We can also do a few simple optimisations here to make the code slightly more efficient, such as storing our element selectors and window width in variables:
(function($) {
$(function() {
var $window = $(window),
newBox = $('<div id="newbox">appended with jQuery</div>'),
box = $('.box');
$window.on('resize', function() {
var windowWidth = $window.width();
if (windowWidth >= 980) {
if(!$.contains(document, newBox[0])) {
box.append(newBox);
}
} else if (windowWidth <= 979) {
if($.contains(document, newBox[0])) {
newBox.remove();
}
}
}).trigger('resize');
});
})(jQuery);
I think you need to add an event listener on the window object, listening for the .resize() event:
https://api.jquery.com/resize/
Then in the callback function you should be able to check whether the new size is below your threshold, so you can remove the div in that case.
$(window).resize(function () {
// Check window width here, and remove div if necessary
})

Why jQuery .width is returning 0 instead of 1 [duplicate]

I want to do:
$("img").bind('load', function() {
// do stuff
});
But the load event doesn't fire when the image is loaded from cache. The jQuery docs suggest a plugin to fix this, but it doesn't work
If the src is already set, then the event is firing in the cached case, before you even get the event handler bound. To fix this, you can loop through checking and triggering the event based off .complete, like this:
$("img").one("load", function() {
// do stuff
}).each(function() {
if(this.complete) {
$(this).load(); // For jQuery < 3.0
// $(this).trigger('load'); // For jQuery >= 3.0
}
});
Note the change from .bind() to .one() so the event handler doesn't run twice.
Can I suggest that you reload it into a non-DOM image object? If it's cached, this will take no time at all, and the onload will still fire. If it isn't cached, it will fire the onload when the image is loaded, which should be the same time as the DOM version of the image finishes loading.
Javascript:
$(document).ready(function() {
var tmpImg = new Image() ;
tmpImg.src = $('#img').attr('src') ;
tmpImg.onload = function() {
// Run onload code.
} ;
}) ;
Updated (to handle multiple images and with correctly ordered onload attachment):
$(document).ready(function() {
var imageLoaded = function() {
// Run onload code.
}
$('#img').each(function() {
var tmpImg = new Image() ;
tmpImg.onload = imageLoaded ;
tmpImg.src = $(this).attr('src') ;
}) ;
}) ;
My simple solution, it doesn't need any external plugin and for common cases should be enough:
/**
* Trigger a callback when the selected images are loaded:
* #param {String} selector
* #param {Function} callback
*/
var onImgLoad = function(selector, callback){
$(selector).each(function(){
if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
callback.apply(this);
}
else {
$(this).on('load', function(){
callback.apply(this);
});
}
});
};
use it like this:
onImgLoad('img', function(){
// do stuff
});
for example, to fade in your images on load you can do:
$('img').hide();
onImgLoad('img', function(){
$(this).fadeIn(700);
});
Or as alternative, if you prefer a jquery plugin-like approach:
/**
* Trigger a callback when 'this' image is loaded:
* #param {Function} callback
*/
(function($){
$.fn.imgLoad = function(callback) {
return this.each(function() {
if (callback) {
if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
callback.apply(this);
}
else {
$(this).on('load', function(){
callback.apply(this);
});
}
}
});
};
})(jQuery);
and use it in this way:
$('img').imgLoad(function(){
// do stuff
});
for example:
$('img').hide().imgLoad(function(){
$(this).fadeIn(700);
});
Do you really have to do it with jQuery? You can attach the onload event directly to your image as well;
<img src="/path/to/image.jpg" onload="doStuff(this);" />
It will fire every time the image has loaded, from cache or not.
You can also use this code with support for loading error:
$("img").on('load', function() {
// do stuff on success
})
.on('error', function() {
// do stuff on smth wrong (error 404, etc.)
})
.each(function() {
if(this.complete) {
$(this).load();
} else if(this.error) {
$(this).error();
}
});
I just had this problem myself, searched everywhere for a solution that didn't involve killing my cache or downloading a plugin.
I didn't see this thread immediately so I found something else instead which is an interesting fix and (I think) worthy of posting here:
$('.image').load(function(){
// stuff
}).attr('src', 'new_src');
I actually got this idea from the comments here: http://www.witheringtree.com/2009/05/image-load-event-binding-with-ie-using-jquery/
I have no idea why it works but I have tested this on IE7 and where it broke before it now works.
Hope it helps,
Edit
The accepted answer actually explains why:
If the src is already set then the event is firing in the cache cased before you get the event handler bound.
By using jQuery to generate a new image with the image's src, and assigning the load method directly to that, the load method is successfully called when jQuery finishes generating the new image. This is working for me in IE 8, 9 and 10
$('<img />', {
"src": $("#img").attr("src")
}).load(function(){
// Do something
});
A solution I found https://bugs.chromium.org/p/chromium/issues/detail?id=7731#c12
(This code taken directly from the comment)
var photo = document.getElementById('image_id');
var img = new Image();
img.addEventListener('load', myFunction, false);
img.src = 'http://newimgsource.jpg';
photo.src = img.src;
A modification to GUS's example:
$(document).ready(function() {
var tmpImg = new Image() ;
tmpImg.onload = function() {
// Run onload code.
} ;
tmpImg.src = $('#img').attr('src');
})
Set the source before and after the onload.
Just re-add the src argument on a separate line after the img oject is defined. This will trick IE into triggering the lad-event. It is ugly, but it is the simplest workaround I've found so far.
jQuery('<img/>', {
src: url,
id: 'whatever'
})
.load(function() {
})
.appendTo('#someelement');
$('#whatever').attr('src', url); // trigger .load on IE
I can give you a little tip if you want do like this:
<div style="position:relative;width:100px;height:100px">
<img src="loading.jpg" style='position:absolute;width:100px;height:100px;z-index:0'/>
<img onLoad="$(this).fadeIn('normal').siblings('img').fadeOut('normal')" src="picture.jpg" style="display:none;position:absolute;width:100px;height:100px;z-index:1"/>
</div>
If you do that when the browser caches pictures, it's no problem always img shown but loading img under real picture.
I had this problem with IE where the e.target.width would be undefined. The load event would fire but I couldn't get the dimensions of the image in IE (chrome + FF worked).
Turns out you need to look for e.currentTarget.naturalWidth & e.currentTarget.naturalHeight.
Once again, IE does things it's own (more complicated) way.
You can solve your problem using JAIL plugin that also allows you to lazy load images (improving the page performance) and passing the callback as parameter
$('img').asynchImageLoader({callback : function(){...}});
The HTML should look like
<img name="/global/images/sample1.jpg" src="/global/images/blank.gif" width="width" height="height" />
If you want a pure CSS solution, this trick works very well - use the transform object. This also works with images when they're cached or not:
CSS:
.main_container{
position: relative;
width: 500px;
height: 300px;
background-color: #cccccc;
}
.center_horizontally{
position: absolute;
width: 100px;
height: 100px;
background-color: green;
left: 50%;
top: 0;
transform: translate(-50%,0);
}
.center_vertically{
position: absolute;
top: 50%;
left: 0;
width: 100px;
height: 100px;
background-color: blue;
transform: translate(0,-50%);
}
.center{
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
background-color: red;
transform: translate(-50%,-50%);
}
HTML:
<div class="main_container">
<div class="center_horizontally"></div>
<div class="center_vertically"></div>
<div class="center"></div>
</div>
</div
Codepen example
Codepen LESS example

Scroll event background change

I am trying to add a scroll event which will change the background of a div which also acts as the window background (it has 100% width and height). This is as far as I get. I am not so good at jquery. I have seen tutorials with click event listeners. but applying the same concept , like, returning scroll event as false, gets me nowhere. also I saw a tutorial on SO where the person suggest use of array. but I get pretty confused using arrays (mostly due to syntax).
I know about plugins like waypoints.js and skrollr.js which can be used but I need to change around 50-60 (for the illusion of a video being played when scrolled) ... but it wont be feasible.
here is the code im using:-
*
{
border: 2px solid black;
}
#frame
{
background: url('1.jpg') no-repeat;
height: 1000px;
width: 100%;
}
</style>
<script>
$(function(){
for ( i=0; i = $.scrolltop; i++)
{
$("#frame").attr('src', ''+i+'.jpg');
}
});
</script>
<body>
<div id="frame"></div>
</body>
Inside your for loop, you are setting the src attribute of #frame but it is a div not an img.
So, instead of this:
$("#frame").attr('src', ''+i+'.jpg');
Try this:
$("#frame").css('background-image', 'url(' + i + '.jpg)');
To bind a scroll event to a target element with jQuery:
$('#target').scroll(function() {
//do stuff here
});
To bind a scroll event to the window with jQuery:
$(window).scroll(function () {
//do stuff here
});
Here is the documentation for jQuery .scroll().
UPDATE:
If I understand right, here is a working demo on jsFiddle of what you want to achieve.
CSS:
html, body {
min-height: 1200px; /* for testing the scroll bar */
}
div#frame {
display: block;
position: fixed; /* Set this to fixed to lock that element on the position */
width: 300px;
height: 300px;
z-index: -1; /* Keep the bg frame at the bottom of other elements. */
}
Javascript:
$(document).ready(function() {
switchImage();
});
$(window).scroll(function () {
switchImage();
});
//using images from dummyimages.com for demonstration (300px by 300px)
var images = ["http://dummyimage.com/300x300/000000/fff",
"http://dummyimage.com/300x300/ffcc00/000",
"http://dummyimage.com/300x300/ff0000/000",
"http://dummyimage.com/300x300/ff00cc/000",
"http://dummyimage.com/300x300/ccff00/000"
];
//Gets a valid index from the image array using the scroll-y value as a factor.
function switchImage()
{
var sTop = $(window).scrollTop();
var index = sTop > 0 ? $(document).height() / sTop : 0;
index = Math.round(index) % images.length;
//console.log(index);
$("#frame").css('background-image', 'url(' + images[index] + ')');
}
HTML:
<div id="frame"></div>
Further Suggestions:
I suggest you change the background-image of the body, instead of the div. But, if you have to use a div for this; then you better add a resize event-istener to the window and set/update the height of that div with every resize. The reason is; height:100% does not work as expected in any browser.
I've done this before myself and if I were you I wouldn't use the image as a background, instead use a normal "img" tag prepend it to the top of your page use some css to ensure it stays in the back under all of the other elements. This way you could manipulate the size of the image to fit screen width better. I ran into a lot of issues trying to get the background to size correctly.
Html markup:
<body>
<img src="1.jpg" id="img" />
</body>
Script code:
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200) {
// function goes here
$('img').attr('src', ++count +'.jpg');
}
});
});
I'm not totally sure if this is what you're trying to do but basically, when the window is scrolled, you assign the value of the distance to the top of the page, then you can run an if statement to see if you are a certain point. After that just simply change run the function you would like to run.
If you want to supply a range you want the image to change from do something like this, so what will happen is this will allow you to run a function only between the specificied range between 200 and 400 which is the distance from the top of the page.
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200 && topPage < 400) {
// function goes here
$('#img').attr('src', ++count +'.jpg');
}
});
});

Make div 'fullscreen' onClick?

I have a div that I want to go full-screen (100% width/height of Window size) onClick of a button.
How would I go about this using Javascript/jQuery?
DEMO
$('div').click(function() {
$(this).css({
position:'absolute', //or fixed depending on needs
top: $(window).scrollTop(), // top pos based on scoll pos
left: 0,
height: '100%',
width: '100%'
});
});
$('div.yourdivclass').click(function(){
$(this).css('height','100%').css('width','100%');
})
What have you tried? What didn't work?
Take a look at that:
http://jsfiddle.net/6BP9t/1/
$('#box').on('click',function(e){
$(this).css({
width:"100%",
height:"100%"
});
});
I would do this:
$('#idOfDiv').click(function() {
$(this).css({position:'fixed', height: '100%', width: '100%'});
});​
jsfiffle: http://jsfiddle.net/P6tgH/
$('div').click(function(){
var win = $(window),
h = win.height(),
w = win.width();
$(this).css({ height: h, width: w });
});
http://jsfiddle.net/TQA4z/1/
This is an alternate to the answer marked as correct. Plus it gives him what he asked for to close the div.
Using toggle class is much easier than having your css in your jquery. Do everything you can do to keep css separate from JavaScript.
For some reason my https is effecting loading of the JavaScript on load of that jsfiddle page. I clicked on the Shield icon in chrome address bar and chose to run scripts.
Toggle Class Demo
Something like
$('#buttonID').click(function() {
$("div > div").toggleClass("Class you want to add");
});

Categories

Resources