Trouble centering and dynamically resizing image using jQuery - javascript

Usually I'm able to figure things out given enough time (hence my first post here), but I've been beating my head against the wall for a while now on this one.
I'm trying to:
Center image using jQuery (it's an <img> tag, not background image on a <div>),
Load the correct image size on (window).load, and
Load a new img file at certain breakpoints as the window is re-sized.
Here is my current attempt. The centering script works perfectly. Also, the correct image file is loaded. However, I cannot get the re-size portion to work when the window is made wider or narrower (the image file does not dynamically reload).
CODE:
<!-- Center Floating Div Elements -->
<script>
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
return this;
}
$(window).load(function(){
$('.laptop').center();
window.onresize = function(event) {
$('.laptop').center();
}
});
</script>
<!-- Load correct image size on window load -->
<script>
$(function(){
if($(window).width() >= 0 && $(window).width() <= 900){
$("img").attr("src","/images/laptop-900.png");
}
else if($(window).width() > 900 && $(window).width() <= 1400){
$("img").attr("src","/images/laptop-1500.png");
}
else{
$("img").attr("src","/images/laptop-2100.png");
}
})
</script>
<!-- Re-load new image size on window resize -->
<script>
$(window).onresize = function(){
if($(window).width() >= 0 && $(window).width() <= 900){
$("img").attr("src","/images/laptop-900.png");
}
else if($(window).width() > 900 && $(window).width() <= 1400){
$("img").attr("src","/images/laptop-1500.png");
}
else{
$("img").attr("src","/images/laptop-2100.png");
}
});
</script>
The relevant HTML is just a tag with a class of "laptop", wrapping around an image tag (which is where I want the image source to dynamically change).
lharby: here was my attempt at your suggestion, couldn't get it to work either:
<script>
var picresize = $(function(){
if($(window).width() >= 0 && $(window).width() <= 900){
$("img").attr("src","/images/laptop-900.png");
}
else if($(window).width() > 900 && $(window).width() <= 1400){
$("img").attr("src","/images/laptop-1500.png");
}
else{
$("img").attr("src","/images/laptop-2100.png");
}
});
$(window).load(function(){
$picresize();
window.onresize = function(event) {
$picresize();
}
});
</script>

So to elaborate on the comments. I made this fiddle:
https://jsfiddle.net/lharby/5p2xdnaf/
There is now a single function called chImage which checks window width and can then be triggered on various events.
I've also stored window width in a variable to make the code a bit cleaner and easier to read (you could also set your sizes in variables, and then change them later if needed, so only write them once).
var chImage = function(){
var winWidth = $(window).width();
if(winWidth >= 0 && winWidth <= 900){
$("img").attr("src","http://placehold.it/350x150");
}
else if(winWidth > 900 && winWidth <= 1400){
$("img").attr("src","http://placehold.it/500x300");
}
else{
$("img").attr("src","http://placehold.it/800x400");
}
};
Then call this function and bind it to whatever events we want.
$(window).on("load resize", function(){
chImage();
});
EDIT
I did move the centering function below to make sure it wasn't intefering with this function, but the centering can be achieved with css. I will try and update.

Chris Coyier has made an utterly interesting article about figuring out responsive images.
The image centering can be done in CSS, no need for scripts. See centering things and solved by flexbox.

Related

Jquery function only loads after page refresh

I have roughly around 50 video thumbnails on a set page.
I would like to resize them depending on the resolution.
What I have tried was using #media query in css that did not work as expected then I moved over to this.
$(document).ready(function(event) {
var width = $(window).width();
// Change thumbnail size if browser width changes (should be in real-time)
if (width <= 1300) {
console.log(width);
$('.mdl-cell').removeClass('mdl-cell--3-col').addClass('mdl-cell--4-col');
} else {
$('.mdl-cell').removeClass('mdl-cell--4-col').addClass('mdl-cell--3-col');
}
});
After inserting that script the video thumbnail size changes but as I adjust the browser the jQuery does not load and resize the thumbnail unless the page is refreshed ?
Im not sure as to why the jQuery is not loading the script in real time as the size (browser) changes.
Languages that I am using in this project : PHP, jQuery
you need to catch window resize event with jQuery and also write your code there.
$(window).resize(function() {
var width = $(window).width();
// Change thumbnail size if browser width changes (should be in real-time)
if (width <= 1300) {
console.log(width);
$('.mdl-cell').removeClass('mdl-cell--3-col').addClass('mdl-cell--4-col');
} else {
$('.mdl-cell').removeClass('mdl-cell--4-col').addClass('mdl-cell--3-col');
}
});
To reduce code repetition you can make a function and call it in both $(window).resize() and $(document).ready()
function onResize() {
var width = $(window).width();
if (width <= 1300) {
$('.mdl-cell').removeClass('mdl-cell--3-col').addClass('mdl-cell--4-col');
} else {
$('.mdl-cell').removeClass('mdl-cell--4-col').addClass('mdl-cell--3-col');
}
}
$(document).ready(onResize);
$(window).resize(onResize);
This should work, but it would be much better if it were done with css. Would love you help you with that if you want to post what you tried. If you do it with css, you will not have the jumping on the page that'll occur when the js loads and changes those classes in and out.
You can do smth like this.
Note: this is untested code
function updateSizes(){
var width = $(window).width();
if (width <= 1300) {
$('.mdl-cell').removeClass('mdl-cell--3-col').addClass('mdl-cell--4-col');
} else {
$('.mdl-cell').removeClass('mdl-cell--4-col').addClass('mdl-cell--3-col');
}
}
$(document).ready(function(event) {
updateSizes();
// do other stuff here
});
$( window ).resize(function() {
updateSizes();
// do other stuff here
});

Javascript scroll addClass

I want my navbar to be transparant on the top and bottom of my page but i want it to not be transparant in the middle. When i have my webpage on full screen this works:
$(window).on("scroll", function () {
if ($(window).scrollTop() > 720 && $(window).scrollTop() < 1450 ) {
$(".nav").addClass("active");
} else {
$(".nav").removeClass("active");
}
})
But when it gets resized this wont work anymore because the sizes change. Is there a way to do this with % instead of just normal numbers so it will be responsive?
It occur because you hardcoded your height values. Check the whole site height, divide it on three and incorporate this variables to your if statement. Every time you resize browser window it will recalculate your new position.
window.addEventListener('resize', function() {
//one third and two third of website
oneThird = window.scrollHeight / 3;
twoThird = onethird * 2;
if ( $(window).scrollTop() > oneThird && $(window).scrollTop() < twoThird ) {
$(".nav").addClass("active");
} else {
$(".nav").removeClass("active");
}
}
You can use Media Queries with JS too, so you can do certain things on your desired window size, this might help https://www.w3schools.com/howto/howto_js_media_queries.asp

fixed navbar issue after resize to page

I have a page if you click you are gonna see demo page and there is a fixed menu which is hidden.
after scroll page to down you'll see fixed menu set as display:block as you see on image:
but after appear if I'm resizing to window and if I turn normal desktop mode after scroll page to up as you see my fixed menu is not hiding
and another problem is if you open page mobile emulator (like on this emulator)[http://mobiletest.me/google_nexus_7_emulator/?u=http://firatabak.com/test/tur_detay.html] normally menu has to be show when I scroll page to down but it's not.
JS CODE
var navOffset = jQuery(".after-scroll-sticky").offset().top;
jQuery(window).scroll(function(){
var scrollPosition = jQuery(window).scrollTop();
if(scrollPosition >= navOffset){
jQuery(".sticky-navbar").fadeIn().addClass("fixed");
}else{
jQuery(".sticky-navbar").fadeOut().removeClass("fixed");
}
});
if ($(window).width() < 768) {
var navOffset2 = jQuery(".after-scroll-sticky").offset().top+200;
jQuery(window).scroll(function(){
var sP = jQuery(window).scrollTop();
if(sP >= navOffset2){
$(".sticky-navbar").addClass("fadeOutRightBig");
$(".menu-btn").fadeIn("fast");
}else{
$(".sticky-navbar").removeClass("fadeOutRightBig");
$(".menu-btn").fadeOut("slow");
}
});
}
Since you're defining the second jQuery.scroll function within an if statement, it only becomes active if the window width is less than 768px at the moment the script runs - it doesn't kick in when the window is resized. Instead you could try this format:
jQuery(window).scroll(function(){
if ($(window).width() < 768) {
// calculations and animation go here
}
});
Or better yet, combine the two jQuery.scroll functions together:
jQuery(window).scroll(function(){
var navOffset = jQuery(".after-scroll-sticky").offset().top,
scrollPosition = jQuery(window).scrollTop();
if ($(window).width() < 768) {
if (scrollPosition >= navOffset + 200) {
// ...
} else {
// ...
}
else if (scrollPosition >= navOffset) {
// ...
} else {
// ...
}
});
Then just make sure that you're undoing the changes made in other cases before applying the new changes.

$(window).width() and $('body').scrollLeft() not working in IE and Firefox

Sample: http://kat.isltest.net/col/
This sample site is working in chrome. The function is the body is centered even it contains a wide div of 1600px. The scrollbar is then by default centered in every window size.
Now, the problem is this is not working in IE and Firefox.
Here's the code:
if ($(window).width() <= 1600) {
$('body').scrollLeft(0);
}
if ($(window).width() <= 1400) {
$('body').scrollLeft(110);
}
if ($(window).width() <= 1360) {
$('body').scrollLeft(130);
}
if ($(window).width() <= 1280) {
$('body').scrollLeft(170);
}
if ($(window).width() <= 1152) {
$('body').scrollLeft(235);
}
if ($(window).width() <= 1024) {
$('body').scrollLeft(300);
}
if ($(window).width() <= 800){
$('body').scrollLeft(400);
}
DO you guys have idea why?
Thanks a lot! :)
You need to wrap you code with a listener that executes when the window is resized, otherwise the scrollbars are adjusted only once:
$(window).on('resize', function() {
/* your code */
});
I guess the reason that chrome adjusts it's vertical scrollbar to the center when the width of the browser window is smaller then 1600px is default behaviour and has nothing to do with your code.
Edit
Further, you need to use $(document).scrollLeft() instead of $('body').scrollLeft() if you want the viewport to scroll.
If you want to do scroll on click any button then you can do following using jquery.
$('#next').click(function(event) {
event.preventDefault();
$('.surr-cor').animate({
scrollLeft: "+=1350px"
}, "slow");
});
Mention event for firefox because it works on events. You can replace .surr-cor to your div element or body

Changing functions based on screen size

I'm trying to execute functions based on the user screen size. I managed to do so with the following code:
var width = $(window).width();
if (width > 1000) {
slideshow();
tablet();
if (width > 1600) {
audio();
}
}
else {
phone();
$('.menu').localScroll();
}
When the user is changing his screen size while he is already inside the website (like resizing or changing orientation mode) the previous functions that were executed are still taking effect, which creates conflict with he latest functions that are trying to get executed.
I tried add the following code to the one listed above:
$(window).resize(function() {
$('.logo').unbind();
$('.menu-item').unbind();
$('.menuList').unbind();
$('.icon-menu').unbind();
$('.menuListItem').unbind();
$('.menu').unbind();
$('.info').unbind();
if (width > 1000) {
slideshow();
tablet();
if (width > 1600) {
audio();
}
}
else {
phone();
$('.menu').localScroll();
}
});
This code .unbind() every element that is being effected by the previous functions when the user resizing the browser, but it still loads the previous functions (phone/tablet).
I'm looking for a way to remove the unnecessary functions when the screen size is being resized.
live example can be viewed at this website
Try this:
function res(){
var width = $(window).width();
$('.logo').unbind();
$('.menu-item').unbind();
$('.menuList').unbind();
$('.icon-menu').unbind();
$('.menuListItem').unbind();
$('.menu').unbind();
$('.info').unbind();
}
$(window).ready(res).resize(res);

Categories