I have no idea from javascript and I need a little help here. From resources here and there I am trying to do the following logic.
When the browser has a width less than 700px then all images that have class "star-wars" will have that class removed.
$(window).resize(function() {
/*If browser resized, check width again */
if ($(window).width() < 700) {
function myFunction() {
var element = document.querySelectorAll('img.has-zoom');
element.classList.remove("has-zoom");
}
}
});
Obviously the above code is wrong. I need you to tell me how the above can be written correctly (if this is the right one).
The document.querySelectorAll('img.has-zoom') will return a NodeList not an element.
You need to loop through the returned list or get the element you want from it to extract the classList from it.
Try :
window.addEventListener('resize', removeClass);
function removeClass() {
width = window.innerWidth || $(window).width();
if ( window.innerWidth < 700) {
var elements = document.querySelectorAll('img.has-zoom');
[].forEach.call(elements, function(el) {
el.classList.remove("has-zoom");
});
}
}
Sample that removes class after 2 seconds:
setTimeout(function() {
var elements = document.querySelectorAll('img.has-zoom');
[].forEach.call(elements, function(el) {
el.classList.remove("has-zoom");
});
}, 2000);
.has-zoom {
border: 3px solid yellow;
}
<img alt="Image 1" src="https://www.gravatar.com/avatar/a29d596b0af040d7def18d1801340a8b" class="has-zoom">
<img alt="Image 2" src="https://www.gravatar.com/avatar/a29d596b0af040d7def18d1801340a8b">
<img alt="Image 3" src="https://www.gravatar.com/avatar/a29d596b0af040d7def18d1801340a8b" class="has-zoom">
Since you are already using jQuery, here is a simple solution:
$(window).resize(function() {
if ($(window).width() < 700) {
$(".has-zoom").removeClass("has-zoom")
}
});
Your code is almost correct.
You can add an event listener to the window to check if it is being resized, and from there check the actual size of the screen and remove the classes where necessary.
<!-- images with class -->
<img class="star-wars" />
<img class="star-wars" />
<img class="star-wars" />
<img class="star-wars" />
<img class="star-wars" />
// javascript
// listen for the window being resized
window.addEventListener('resize', checkScreenSize);
// function to call every time the window is resized
function checkScreenSize() {
// check size of window
if ( window.innerWidth < 700) {
// loop through images with class name attached
var images = document.getElementsByClassName('star-wars');
for ( var i = 0; i < images.length; i++ ) {
// remove class from each image
images[i].classList.remove('star-wars')
}
}
}
You can add another conditional statement to add the class back on if the window gets resized above 700px again.
var classNameRemoved = false;
$(window).resize(function () {
if ($(window).width() < 700 && !classNameRemoved) {
var elements = document.querySelectorAll("img.has-zoom");
elements.forEach(function (element) {
element.classList.remove("has-zoom");
});
classNameRemoved = true;
}
});
As you said, below code will remove the elements which has class 'star-wars' when the browser width is less than 700px
$(document).ready(function(){
$(window).resize(function(){
if ($(window).width() < 700) {
const element = document.querySelectorAll('img.has-zoom');
if (element.classList.contains("classToBeRemoved")) {
element.classList.remove("classToBeRemoved");
}
}
});
});
Related
Two questions:
Focus on the part of 'Get early access' bar. It is positioned with position:relative and I want to have it sticky once you move to the 2nd section. I've tried to add helper with the same height in order to get smooth transition when I change the .class to fixed. But not working.
This with helper in previous websites helped me but now it doesn't work and it really bothers me.
What would be alternative to position sticky which works in all browsers? In this particular case, how needs jquery to look like?
Thanks in advance.
/**
* Zirelco
* Custom JS functions
*/
jQuery(document).ready(function ( $ ) {
var mn = $("#sticky-wrapper");
mns = "nav--scrolled";
hdr = $("#top-wrapper-v1").height();
$(window).scroll(function() {
if( $(this).scrollTop() > hdr ) {
mn.addClass(mns);
} else {
mn.removeClass(mns);
}
});
$('.cookies .btn').on('click', function() {
if ($('.cookies').css('opacity') == 0) {
$('.cookies').css('opacity', 1);
}
else {
$('.cookies').addClass('none');
}
});
});
Edit V3
Try this Code instead of yours:
(function(selector) {
selector = selector || '#sticky-wrapper';
var stickyWrapper = document.querySelector(selector)
var stickyTrigger = document.createElement('div')
stickyTrigger.classList.add('sticky-trigger')
stickyWrapper.parentElement.insertBefore(stickyTrigger, stickyWrapper)
var listener = function (e) {
if (stickyTrigger.getBoundingClientRect().top < 0) {
stickyWrapper.classList.add('sticky');
} else {
stickyWrapper.classList.remove('sticky');
}
}
var onScroll = document.addEventListener('scroll', listener);
}('#sticky-wrapper'))
What this does is:
create a .sticky-trigger element
insert this right before #sticky-wrapper
watch for scroll event of document
check the top property of getBoundingClientRect of the .sticky-trigger element
toggle the sticky class of #sticky-wrapper depending on the sign (positive or negative) of that top value
You don't have to change your HTML output at all
Old V1
You use the height of the #top-wrapper-v1 <section> as trigger for the class toggle. But you totally forget the to calc the <header> height as well.
To prevent such mistakes just go for the top edge of the '#sticky-wrapper' as a trigger
// $(window).scroll(function(e) {
// if( $(this).scrollTop() > mn.offset().top ) {
// mn.addClass('sticky');
// } else {
// mn.removeClass('sticky');
// }
//});
Old V2
Because of the comment of the asker, this is an improved way of doing it.
In the previous example, the measurement of the offset().top of #sticky-wrapper is immediately set to 0 caused by position: fixed. In order to break this issue, we wrap the #sticky-wrapper in a trigger element, measure the offset().top of that element as trigger. This trigger element will remain in the document flow and will not be fixed
HTML
<!--
<section id="sticky-trigger">
<section id="sticky-wrapper" class="">
<div class="container" style="position: fixed;top: 0;">
Other content
</div>
</section>
</section>
-->
JavaScript
// var trigger = document.querySelector('#sticky-trigger')
// $(window).scroll(function(e) {
//
// if( $(this).scrollTop() > trigger.offset().top ) {
// mn.addClass('sticky');
// } else {
// mn.removeClass('sticky');
// }
// });
I created a attribute for img tag as in the example code like data-tablet, data-mobil
<div class="myDiv">
<img src="img-1.jpg" data-tablet="img-2.jpg" data-mobil="img-3.jpg">
</div>
and I want if my screen change for tablet my img src change with data-tablet or my screen is for mobil my src must change with data-mobil
MY JS
$(document).ready(function(){
$(window).resize(function(){
var tabletSrc = $(".main-carousel img").attr("data-tablet");
var mobilSrc = $(".main-carousel img").attr("data-mobil");
if($(window).width() <=768){
$('img').attr('src',tabletSrc);
}
if($(window).width() <=480 ) {
$('img').attr('src',mobilSrc);
}
});
});
click to see my works
question is how can I do that I want if u click you gonna see nothing work
note: I don't want to use srcset or css
Please see this CodePen for a working version.
There were some issues with your code:
Both the case for mobile and tablet was executed in the mobile case.
$(".main-carousel img") is a collection of images. Instead of that, you probably want to operate on a single image. This can be done with the help of .each().
Here is the relevant code:
$(window).resize(function() {
if ($(window).width() <= 480) {
$('img').each(function() {
$(this).attr('src', $(this).attr('data-mobil'));
});
} else if ($(window).width() <= 768) {
$('img').each(function() {
$(this).attr('src', $(this).attr('data-tablet'));
});
}
});
Use srcset instead of js based validations for device dimensions.
<img src="images/space-needle.jpg"
srcset="images/space-needle.jpg 200w, images/space-needle-2x.jpg 400w,
images/space-needle-hd.jpg 600w">
So, now the browser will automatically device which image to download and show depending on the browser dimensions.
Check out more
https://www.sitepoint.com/how-to-build-responsive-images-with-srcset/
You can try this for you carousel multiple images
function makeResize(){
var imageSrc = $(".myDiv img");
if($(window).width() <=768 && $(window).width()>480){
$(imageSrc).each(function(key,value){
$(value).attr('src',$(value).data('tablet'));
});
}else if($(window).width() <=480 ) {
$(imageSrc).each(function(key,value){
$(value).attr('src',$(value).data('mobile'));
});
}else{
$(imageSrc).each(function(key,value){
$(value).attr('src',$(value).data('default'));
});
}
}
$(document).ready(function(){
$(window).resize(function(){
makeResize();
});
makeResize();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myDiv">
<img src="org1.jpg" data-default="org1.jpg" data-tablet="tablet1.png" data-mobile="mobile1.jpg">
<img src="org2.jpg" data-default="org2.jpg" data-tablet="tablet2.png" data-mobile="mobile2.jpg">
<img src="org3.jpg" data-default="org3.jpg" data-tablet="tablet3.png" data-mobile="mobile3.jpg">
</div>
Note Copy and add proper image source then try. Above code will work for multiple images.
You are using wrong class name. Your div has class "myDiv" and you are selecting by "main-carousel"
$(document).ready(function(){
$(window).resize(function(){
var tabletSrc = $(".myDiv img").attr("data-tablet");
var mobilSrc = $(".myDiv img").attr("data-mobil");
if($(window).width() <=768){
$('img').attr('src',tabletSrc);
}
if($(window).width() <=480 ) {
$('img').attr('src',mobilSrc);
}
});
});
Here is codepen
Keep the short width first. Your validation always goes for tablet first. since 480 < 768
Change your conditions like this.
$(window).resize(function(){
var tabletSrc = $(".someDiv img").attr("data-tablet");
var mobilSrc = $(".someDiv img").attr("data-mobil");
var imgSrc = "defaultImageSrc" //src for default image
var windowWidth = $(window).width();
if(windowWidth <= 480 ) { //first small width
imgSrc = mobilSrc;
}else if(windowWidth <= 768){ //next larger one
imgSrc = tabletSrc;
} //if else default will there for you which is initialised there.
});
Try this:
$(window).resize(function(){
var realImg = $(".main-carousel img").attr();
var tabletSrc = $(".main-carousel img").data("tablet"); //use .data instead of attr
var mobilSrc = $(".main-carousel img").data("mobil");
if($(this).width() <= 768){
$('img').attr('src',tabletSrc);
}
else if($(this).width() <= 480 ) { // use else if instead of if
$('img').attr('src',mobilSrc);
}
else{
$('img').attr('src',realImg);
}
});
I have code written to find the src of all images inside a particular div and change the src name when the window is less than 900 wide. It works fine upon page refresh, but when I resize the window it continuously runs the code and I get this error
GET
file://macintosh%20hd/Users/jessicamele/Desktop/tom%20mendicino/images/boys3_small_small_small_small.jpg
net::ERR_FILE_NOT_FOUND
It just keeps adding the "_small" over and over again. Here is my code:
<div class="threePicsBoys group">
<img src="images/boys3.jpg" alt="street signs" class="boysPics1">
<img src="images/boys2.jpg" alt="city house" class="boysPics2">
<img src="images/boys1.jpg" alt="2 boys" class="boysPics1">
<img src="images/boys4.jpg" alt="philly signs" class="boysPics2">
<img src="images/boys5.jpg" alt="religious statue" class="boysPics1">
</div>
$(function() {
if (windowWidth <= 900) {
var img = $(".threePicsBoys.group").find("img").map(function() {
var src = $(this).attr("src");
var newName = src.replace(".jpg","_small.jpg");
$(this).attr("src",newName);
});
}
});
}
I could really use some help.
This script will check if the window is so thin that it has to change the src, but will also revert the changes when it have become wider than 900.
I slightly changed the mechanics to make it work. windowWidth, for example, wasn't a declared variable, and the rest didn't seem to do that much either.
var thinWindow = false;
$(window).on('load resize', function(){
if($(window).width() <= 900){
if(!thinWindow){
$('.threePicsBoys.group img').each(function(){
var src = $(this).attr("src");
var newSrc = src.replace(".jpg","_small.jpg");
$(this).attr("src", newSrc);
})
thinWindow = true
}
}else{
if(thinWindow){
$('.threePicsBoys.group img').each(function(){
var src = $(this).attr("src");
var newSrc = src.replace("_small.jpg",".jpg");
$(this).attr("src", newSrc);
})
thinWindow = false
}
}
})
Hope this helps
This code will loop forever when window is less than 900 width. If you wish to you only run on window change width you must add the correct event binding
$(window).resize(function() {
if (windowWidth <= 900)
{
var img = $(".threePicsBoys.group").find("img")
var src = img.attr("src");
if (!(src.indexOf("_small.jpg") > -1))
{
var newName = src.replace(".jpg","_small.jpg");
img.attr("src",newName);
}
}
});
I have this function that moves a HTML element around the DOM based on whether the window size is less than 640px or more. I'm moving the image with prepend and append, but because the function fires every time the window is resized I think I'm asking for performance issues.
The code:
function moveDealsImage() {
var mobile_width = 640;
var wi = $(window).width();
if (wi < mobile_width) {
$( ".deals-header" ).prepend( $("div.htp") );
} else {
$( ".deals-header" ).append( $("div.htp") );
}
}
window.addEventListener("resize", moveDealsImage);
moveDealsImage();
I need to keep the listener in there.
Is there a way to do that, but then only prepending/appending the element once each time that the if or else statements become true? (instead of it happening on every pixel change)
There are a few things that you can do to optimize this.
A first option is to only execute your moveDealsImage function when the state changes from mobile to desktop or reverse. All the other resizes can just be ignored.
This can be accomplished by using something like following code:
var mobile_width = 640;
var is_mobile = (window.innerWidth <= mobile_width);
function moveDealsImage(e) {
// Only execute the function when then state changes from mobile to desktop or reverse
if(
! is_mobile && window.innerWidth > mobile_width ||
is_mobile && window.innerWidth <= mobile_width
)
return;
// Update state
is_mobile = (window.innerWidth <= mobile_width);
console.log('your code here');
}
window.addEventListener("resize", moveDealsImage);
moveDealsImage();
Another and better solution would be to use CSS media queries. This can be done with the following CSS and HTML.
.desktop-deals-header {
display: block;
}
.mobile-deals-header {
display: none;
}
#media only screen
and (max-width : 640px) {
.desktop-deals-header {
display: none;
}
.mobile-deals-header {
display: block
}
}
and in your HTML you add two headers, one for desktop and one for mobile.
<div class="mobile-deals-header">Mobile header</div>
<div class="desktop-deals-header">Desktop header</div>
I want to fade in multiple images at the same time as the page loads. Just like this website does it: http://www.struckaxiom.com/work. I have the script to do it only on one image, but I want to have more images included.
This is the single photo script. Please help.
document.write("<style type='text/css'>#thephoto {visibility:hidden;}</style>");
function initImage() {
imageId = 'thephoto'
image = document.getElementById(imageId);
setOpacity(image, 0);
image.style.visibility = "visible";
fadeIn(imageId,ImageId2,0);
}
function fadeIn(objId, opacity) {
if (document.getElementById) {
obj = document.getElementById(objId);
if (opacity <= 100) {
setOpacity(obj, opacity);
opacity += 10;
window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 100);
}
}
}
function setOpacity(obj, opacity) {
opacity = (opacity == 100)?99.999:opacity;
// IE/Win
obj.style.filter = "alpha(opacity:"+opacity+")";
// Safari<1.2, Konqueror
obj.style.KHTMLOpacity = opacity/100;
// Older Mozilla and Firefox
obj.style.MozOpacity = opacity/100;
// Safari 1.2, newer Firefox and Mozilla, CSS3
obj.style.opacity = opacity/100;
}
window.onload = function() {initImage()}
// -->
</script>
Thanks!
Simple array and loop are all you need.
First, add such array on top of the code:
var images = [ "thephoto1", "thephoto2", "thephoto3" ];
(With the ID of all desired images)
Next change the function name to initImages to reflect the fact it will initialize more than one image and finally add that loop:
function initImages() {
for (var i = 0; i < images.length; i++) {
imageId = images[i];
image = document.getElementById(imageId);
setOpacity(image, 0);
image.style.visibility = "visible";
fadeIn(imageId, 0);
}
}
That's it, no need to touch the other functions.
Live test case with cute cats: http://jsfiddle.net/yahavbr/e863X/ :-)
You could just wrap all of your images in a single container like this:
<div id="imageContainer">
<img src="img1.jpg">
<img src="img2.jpg">
<img src="img2.jpg">
</div>
Change your CSS to this:
<style type='text/css'>#imageContainer {visibility:hidden;}</style>
Change your first function to this:
function initImage() {
containerId = 'imageContainer'
container = document.getElementById(containerId);
setOpacity(container, 0);
container.style.visibility = "visible";
fadeIn(containerId,0);
}
By running the fading effect on the container you can then add as much content to the container and it will all fade in together and you never have to update your code.
The way they are doing is using jQuery (an excellent implementation). All of the images are in the same container and are selected using the jQuery class selector. Then they fade in all elements that fit within the viewable area. Their js file is not minimized so you could reverse engineer most of that functionality. The important thing to note is not that it is showing each row at a time but every element that fits in the viewing area. Their key function looks like this:
var elTop = $(el).offset().top - $(window).scrollTop();
var elHeight = $(el).height();
// if between top of footer and top of window
if (elTop + elHeight > 40 && elTop < $(window).height()) {
if ($.inArray($(el).attr("data-unique-id"), elementsInView) < 0) {
addToView(el);
}
} else {
if ($.inArray($(el).attr("data-unique-id"), elementsInView) >= 0) {
removeFromView(el);
}
}
addToView and removeFromView add and remove the element from an array, then fade is executed on the array.