Add class to image depending on image width - javascript

I have a list of images where the width is either 226px or 300px. I want to change the css when the image have the smaller width, 226px. It is the right value on "plus" that should be changed
The HTML looks like following:
<div class="item-image">
<div class="plus-wrapper">
<div class="plus"></div>
<img src="source_to_image" alt="">
</div>
</div>
And it is a loop so it will be several images displayed.
My JS + jQuery so far look like this:
var image = $('.plus-wrapper img');
image.each(function () {
var that = $(this);
if (that.width() < 250) {
that.next('.plus').css('right', '41px');
}
});
But the CSS is not changed. Any idea what I am doing wrong?

Change your code to
$(window).load(function(){
var image = $('.plus-wrapper img');
image.each(function () {
var that = $(this);
if (this.width < 250) {
that.prev().css('right', '41px');
}
});
});
The changes are
use this.width since images have a width property of their own..
use .prev() instead of .next() since the div is the previous element in the DOM
call everything inside the window.load event to be sure the images are loaded (and so they have a width)

You should be using the siblings selector
var image = $('.plus-wrapper img');
image.each(function () {
if ($(this).width() < 250) {
$(this).siblings('.plus').css({'right' : '41px'});
}
});

Related

Gif image not animate after refreshing the page

I have some gif images on my website that I want to animate once you scroll to that part of the page. I have some JavaScript code that hides those gifs then shows them once you get to that part of the page. The issue I am having is that those gifs start animating before I scroll to that part of the page. Another issue I am having is that once I refresh the page the gifs will sometimes animate, but I would like them to animate each time the page gets refreshed.
Here is the link to my website: http://lam-parker.github.io/my_portfolio_website/
This isn't all of the gifs but here's is the portion of my html where my gifs are:
<div class="row4">
<h1 id="title3">Software Skills</h1>
<div class="col-md-2 col-sm-4 col-xs-6">
<img src="img/software-skills/photoshop.gif">
</div>
<div class="col-md-2 col-sm-4 col-xs-6">
<img src="img/software-skills/indesign.gif">
</div>
</div>
Here is the .show()/.hide() JavaScript I added to the gifs section:
$(window).scroll(function() {
if ($(window).scrollTop() > 70) {
$('.row4').show("slow");
} else {
$('.row4').hide();
}
});
I would appreciate it if someone could help me. Thanks in advance.
I think the only way to 'control' them would be to reassign the src attribute :
Demo
img {
opacity: 0;
}
$(window).scroll(function() {
var current = $(this).scrollTop(),
path = 'animated.gif',
visible = $('img').css('opacity') != 0;
if (current > 200) {
if (!visible) $('img').attr('src', path).fadeTo(400,1);
}
else if (visible) $('img').fadeTo(0,0);
});
Update - by request some code that makes it possible to loop through all animated gifs :
Pen
$(function() {
var target = $('.anigif'),
path = [], zenith, nadir, current,
modern = window.requestAnimationFrame;
target.each(function() {
path.push(this.src);
});
$(window).on('load resize', storeDimensions).on('load scroll', function(e) {
current = $(this).scrollTop();
if (e.type == 'load') setTimeout(inMotion, 150);
else inMotion();
function inMotion() {
if (modern) requestAnimationFrame(checkFade);
else checkFade();
}
});
function storeDimensions() {
clearTimeout(redraw);
var redraw = setTimeout(function() {
zenith = []; nadir = [];
target.each(function() {
var placement = $(this).offset().top;
zenith.push(placement-$(window).height());
nadir.push(placement+$(this).outerHeight());
});
}, 150);
}
function checkFade() {
target.each(function(i) {
var initiated = $(this).hasClass('active');
if (current > zenith[i] && current < nadir[i]) {
if (!initiated) $(this).attr('src', path[i]).addClass('active').fadeTo(500,1);
}
else if (initiated) $(this).removeClass('active').fadeTo(0,0);
});
}
});
It will reinitiate them when they come into view (bottom and top) and fade them out when leaving the screen. All it needs is for the animated gifs to have a common class, assigned to the variable target. If the page contains only gifs and no other <img> tags you could even use $('img') and leave out the class. Looks like quite a bit of code but it has some debouncing and other optimisation.
B-)
You need to use CSS opacity 1 or 0 to show or hide your element. That is only way from "old-school". Second thing is to use relative position and move out of screen. Also you can resize image from original size to 1x1px to original size but that is a bad way.

How replace img based on window size

I am trying to replace img src based on window size. This is not a background-image. For mobile size my image needs to be different color/image then larger screens. It is easy to change size of image with css but I think I need to use Jquery to replace image src but cant figure it out yet. Any pointers?
here is my html
<a href="" class="logo">
<img id="brand" src="assets/img/image.png" alt="Image">
</a>
here is my js
$(document).ready(function(){
var windowSize = $( window ).width();
if (windowSize < 400 ) { $('#brand').attr('src', 'assets/img/logo-2.png')};
});
ALL this seems to do is change on load img src not change on window size or resize window.
--edit -- form humbolight
$(function(){
var $window = $(window);
var toggleImage = function toggleImage($el, src){
$el.attr('src',src);
};
$window.on('resize',function(){
if ($window.width() < 385){
//mobile
toggleImage($('#brand'),'assets/img/image.png');
} else {
//landscape tablet/desktop
toggleImage($('#brand'),'assets/img/logo-2.png');
}
});
});
What you are attempting to accomplish would require listening to the resize event on the window element and changing the src based on the changing width (preloading images wouldn't hurt):
$(function(){
var $window = $(window);
var toggleImage = function toggleImage($el, src){
$el.attr('src',src);
};
$window.on('resize',function(){
if ($window.width() < 768){
//mobile
toggleImage($('#two_size_img'),'img#1x.png');
} else {
//landscape tablet/desktop
toggleImage($('#two_size_img'),'img#2x.png');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img id="two_size_img" src="img#1x.png" />
To accomplish the same end, I would favor toggling a background-image, handled entirely with CSS, or similarly, rendering both elements (one img per image wanted) and showing/hiding the desired image -- again, entirely with CSS.

How to add a height attribute to img tag?

For example, I have lots of images, all images' original width is 100px, but original height is different. How can I add height attribute based on the original height of these images automatically. Such as
<img src="picture.jpg" width="100" height="132">
<img src="picture.jpg" width="100" height="45">
<img src="picture.jpg" width="100" heighst="321">
<img src="picture.jpg" width="100" height="136">
<img src="picture.jpg" width="100" height="214">
......
I try this, I try to get the original height of each images first,
$(document).ready(function() {
$items = $('img');
$.each($items,function(k, v){
console.log(v.naturalHeight);
});
});
it doesn't work
This works sometimes
$items = $('img');
$.each($items,function(k, v){
$(this).load(function(){
console.log($(this)[0].naturalHeight);
$(this).attr('height', $(this)[0].naturalHeight);
});
});
The problem is that how can I make sure all the images have been loaded before I run the script?
Easiest implementation would be to wait for all the images to load, and then setting the attribute using JavaScript (I notice you're using jQuery).
$(window).load(function(){
$.each($('img'), function(){
// Set the height, hard-style!
$(this).attr('height', $(this).height());
});
});
Obviously, there are other - arguably better - ways to do this (like setting each image's height as it loads), but this should suffice.
Have a look at the imagesLoaded jQuery plugin and maybe wrap the above $.each() in one of it's methods, e.g.:
imagesLoaded( '#yourContainer', function() {
$.each($('img'), function(){
$(this).attr('height', $(this).height());
});
});
If you do not attribute a height, the image will keep its original proportion.
Otherwise, you can do it with JavaScript, like this :
function loaded() {
var img = document.getElementById("imgID");
img.style.height = img.height;
}
EDIT :
If you don't have IDs on your images :
function loaded() {
var images = getElementsByTagName(img);
for(i = 0; i < images.length; i++) {
images[i].style.height = img.height;
}
}
(function(){
$("img.adjust-image").height("100px");
})()
$('img.adjust-image') returns array of all <img>elements that has class=adjust-image class attribute. So We can add the height property for all the images that goes under it.
You don't need to add height attribute at all, only width, and image will scale automatically.

Creating Image slider using only jQuery

I'm trying to create an image slider using Jquery.
What I have is a main div with 3 sub divs with images.
Take a look at this fiddle. FIDDLE
Ok now i got the design just the way I want it. What is missing is the functionality.
When i hover over the div or the images, I want it to act like a clockwise slider.
This may look a bit confusing. Take a look at this demo. This is what i want.
DEMO
This is what i want.The right div gets filled with the middle image src , the middle div gets the left div src. The left div get an new src from an array of images i have defined. Currently i can only change one image div at a time.
However I don't want to use any more plugins. Only Jquery plugin. A CSS only solution would be the best but I do not think it will be possible.
JQUERY
$('.maindiv img').mouseover(function () {
var image = this;
loop = setInterval(function () {
if (i < images.length - 1) {
i++;
$(image).attr('src', images[i]);
} else {
i = 0;
$(image).attr('src', images[i]);
}
}, 1500);
EDIT: I managed to get one part of this working. CHECK THIS.Just need to add fade effect Now the problem is after the images in the array end the first images dont loop back... Had not thought of this before.Does Anybody know how i can get over this issue?
Mabye something like this:
jQuery(document).ready(function () {
var images = [];
var loop;
var i = 0;
images[0] = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ1GfA01TRDgrh-c5xWzrwSuiapiZ6b-yzDoS5JpmeVoB0ZCA87";
images[1] = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQQSyUWiS4UUhdP1Xz81I_sFG6QNAyxN7KLGLI0-RjroNcZ5-HLiw";
images[2] = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT_E_OgC6RiyFxKtw03NeWyelfRgJ3Ax3SnZZrufNkUe0nX3pjQ";
$('img', '.maindiv').mouseover(function () {
//Get divs inside main div and reverse them, so right is first
var divs = $($('div','.maindiv').get().reverse());
//Set up loop
loop = setInterval(function(){
divs.each(function(key, div){
if (divs[key+1])
{
//All divs gets image src from previous div > img
$('img', div).attr('src', $('img', $(divs[key+1])).attr('src'));
}
else
{
//This is left div
if (images && images[i])
{
//If picture url not in array then add it
if ($.inArray($('img', div).attr('src'), images) == -1)
{
images.push($('img', div).attr('src'));
}
$('img', div).attr('src', images[i]);
i++;
if (i>= images.length) i = 0;
}
}
});
}, 1500);
}).mouseout(function(){
clearInterval(loop);
});
});
Fiddle

Live listener on other's resizable div width

Lets say we have one div:
<div id="left">Some content</div>
Div with id "left" is resizable div (it can be re sized with mouse in the browser) and when re-sized, it receives CSS style for current width like this:
<div id="left" style="width: 289px;">Some content</div>
What I want to achieve is to read width value on live event (or something like that) of #left div and based on that value add some conditions (it must be live event, not to read it on click or on mouse release click etc.) ... Thanks for your help in advance!
SOLUTION:
You can use your custom bind function to achieve this:
(function(){
var interval;
jQuery.event.special.liveresize = {
setup: function(){
var self = this,
$this = $(this),
$originalContent = $this.width();
interval = setInterval(function(){
if($originalContent != $this.width()) {
$originalContent = $this.width();
jQuery.event.handle.call(self, {type:'liveresize'});
}
},100);
},
teardown: function(){
clearInterval(interval);
}
};
})();
And then just call it:
$(function() {
$('#left').bind('liveresize', function() {
var actual_width = $(this).width();
if(actual_width < 930)
{
$('#left').addClass('ng-av-small-left');
$('#left').addClass('ng-av-small-right');
} else
{
$('#left div.block div.left').removeClass().addClass('left');
$('#left div.block div.right').removeClass().addClass('right');
}
});
});
you can get it like this
var j = $('.box').height();
check this links for resizable div tags
please refer this links
http://jqueryui.com/demos/resizable/#method-option
to get size of div
http://www.ezineasp.net/post/Javascript-Get-Height-of-Div-onclick.aspx

Categories

Resources