Assign an image as a css background image - javascript

I'm working on a responsive slider, it's not that easy. Basically it must works from 320px to 1920px, with a fixed height.
So its giving me a headache, I have an easy fix : instead of using the a > image, I will assign the image url as background image for the a, then set the image opacity to 0. So, I will be able to use the cover+center background properties and my slider will be perfect.
But I have problems doing that because I'm unsure how to do it, I spent time yesterday but couldn't assign the image as background.
Here is what the markup looks like (I removed unecessary blocks, just keeping the most importants)
<div class="slide-image">
<a href="xyz.com">
<img src="image.com/img.jpg">
</a>
</div>
<div class="slide-image">
<a href="zxy.com">
<img src="image.com/img2.jpg">
</a>
</div>
etc ..
I tried that code which doesnt work, the variable gets a value but nothing is assigned :
$(function() {
if ($('.slider').length) {
$('.slider').slick({});
$('.slide-image').each(function() {
var img = $('img', this).attr('src');
$('a', this).css('background-image', 'url(' + img + ')url');
};
}
});

You're trying to read "src" attribute, but you've set "url" in your HTML. Change your JS:
var img = $('img', this).attr('url');
Also you're assigning wrong style. It should be:
$('a', this).css('background-image', 'url(' + img + ')');

Note you have an error in this line:
$('a', this).css('background-image', 'url(' + img + ')url');
------------------------------^
It must be
$('a', this).css('background-image', 'url(' + img + ')');
And <img> tag is bad,
<img url=""> BAD
<img src=""> GOOD

Related

how to get the height and width of image in javascript?

I have a code where I am trying to get all images tag height and width.
var img = $('.data').find('img');
$.each($(img), function() {
console.log('first', this.height, $(this).height, $(this).height());
console.log('second', $(this).clientHeight, $(this).naturalHeight);
console.log('third', $(this)[0].height, $(this)[0].clientHeight, $(this)[0].naturalHeight);
console.log($(this).attr('height'), $(this).prop('height')); });
Even i tried for img in loop.
tried the same with width , the result will be either 0 or undefined.
tried same thing for width.
Can you tell me where I am doing wrong
You are passing $(img) this should be only img inside you $.each.Also you where printing console.log('first',.. instead of this if your image has name attribute use that .
Here is demo code :
var img = $('.data').find('img');
$.each(img, function() {
console.log($(this).attr("name") + "-> Height: " + $(this)[0].height + " Width:" + $(this)[0].width);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="data">
<img name="image1" src=" https://twimg0-a.akamaihd.net/a/1350072692/t1/img/front_page/jp-mountain#2x.jpg" style="height:70px;width:70px">
<img name="image2" src=" https://twimg0-a.akamaihd.net/a/1350072692/t1/img/front_page/jp-mountain#2x.jpg" style="height:40px;width:40px">
<img name="image3" src=" https://twimg0-a.akamaihd.net/a/1350072692/t1/img/front_page/jp-mountain#2x.jpg" style="height:50px;width:50px">
</div>
i was not getting the height and width of an image because the image load event happens very late in the load process
Finally I found an answer
var img = $('.data').find('img');
$.each(img, function() {
$(this).bind('load', function() {
console.log($(this).height);
}
});
it worked for both img and $(img)

Change background url of div via HTML tag

I have a div (CSS - height: 250px, width: 70%) and I have set a background via CSS. I want to change the background onhover.
That's simple, I know. But I want to get sources of backgrounds from the HTML tag.
Ex.:
<div class="somediv" data-imgbefore="img1.png" data-imgafter="img2.png"></div>
Can anyone help me please?
If you're not using jQuery you can achieve the desired effect using basic Event Listeners. https://jsfiddle.net/gnu9utos/3/
// first get the element that we'll be interacting with
var element = document.querySelector('.somediv');
// assuming we managed to successfully get the element from the document
if(element) {
var before = element.getAttribute('data-imgbefore');
var after = element.getAttribute('data-imgafter');
if(before && after) {
element.style.background = 'url(' + before + ')'; // set the initital state
element.addEventListener('mouseover', function(event) {
element.style.background = 'url(' + after + ')';
});
element.addEventListener('mouseout', function(event) {
element.style.background = 'url(' + before + ')';
});
}
}
You might want to add a check for mouseleave to revert the image back to it's original state and add a little bit of css.
I hope this was helpful.
you can do this with this simple JQ
maybe it's not the best solution but it works.i added background-color so you can see the change. but you can remove that and leave only background-image
see here
jsfiddle
made 2 variables and assigned them to each image ( before and after img ) to each div with class .somediv
add an initial background-image to the div
then at hover, the background-image of the div changes between imgbefore and imgafter
jq :
$(".somediv").each(function(){
var imgbef = $(this).data("imgbefore"),
imgaft = $(this).data("imgafter")
$(this).css({'background-image': 'url(' + imgbef + ')','background-color':'red'});
$(this).hover(function(){
$(this).css({'background-image': 'url(' + imgaft + ') ','background-color':'blue'});
}, function(){
$(this).css({'background-image': 'url(' + imgbef + ')','background-color':'red'});
});
});
HTML :
<div class="somediv" data-imgbefore="img1.png" data-imgafter="img2.png"></div>
CSS :
.somediv {
height:250px;
width:70%;
}
let me know if it helps
You can easily achieve that with javascript. You can also add an onmouseleave function, but this time, passing this.dataset.imgbefore as second argument.
changebg = function(el, i) {
var t = "url("+i+")";
el.style.backgroundImage = t;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="somediv" id="mydiv" data-imgbefore="http://lorempixel.com/400/200/sports" data-imgafter="http://lorempixel.com/400/200/animals" onmouseover="changebg(this, this.dataset.imgafter)">Lorem</div>
</body>
</html>
You can add all the div that you like and change only the data-imgbefore and data-imgafter !!!
$(document).ready(function(){
$('.somediv').each(function( index, value ) {
var img = $(this).attr('data-imgbefore');
$('.somediv').css({'background-image':'url('+ img +')', 'background-size':'200px 200px'});
});
//$('.somedive').css({'background-image':'url("http://www.palladio-tv.it/Internet/siti_gec/2B/Manzan_Disney/codice/Pippo.png")', 'background-size':'200px 200px'});
$('.somediv').hover(
function () {
var img = $(this).attr('data-imgafter');
$(this).css({'background-image':'url('+ img +')', 'background-size':'200px 200px'});
},
function () {
var img = $(this).attr('data-imgbefore');
$(this).css({'background-image':'url('+ img +')', 'background-size':'200px 200px'});
}
);
});
.somediv {width:200px;height:200px;border:1px solid #F2F2F2;border-radius:4px;display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="somediv" data-imgbefore="http://www.palladio-tv.it/Internet/siti_gec/2B/Manzan_Disney/codice/Pippo.png" data-imgafter="http://www.filastrocche.it/contenuti/wp-content/uploads/2001/04/pippogoofy_352.jpg"></div>
<div class="somediv" data-imgbefore="http://www.palladio-tv.it/Internet/siti_gec/2B/Manzan_Disney/codice/Pippo.png" data-imgafter="http://www.filastrocche.it/contenuti/wp-content/uploads/2001/04/pippogoofy_352.jpg"></div>
Cheers!!!
Not sure if I understand what you are trying to accomplish. Why don't you abandon the HTML tag requirement and just try css :hover?
#somediv {
background: url(...);
}
#somediv:hover {
background: url(...); /* different url */
}
http://www.w3schools.com/cssref/css3_pr_background.asp

fadeOut then fadeIn sequentially

I'm trying to fade out one image, then fade in another image in the same spot.
So far I've got this fiddle, but you can see it changes the image before the .fadeOut() function finishes, when changing image via clicking thumbs. I've read that jQuery doesn't run sequentially as standard (which my code is assuming it does), so I tried adding in the completed function, like so:
$('#image').fadeOut('fast', function() {
$('#image').html('<img src="' + image + '" class="image"/>');
$('#image').fadeIn('fast');
});
However my issue is still present. What should I do to fix this?
I wouldn't destroy and recreate the elements; I'd just update the attributes. I'd also include a .stop(true, true) to cancel any previous animation and jump straight to the end before starting the fadeout, in case someone clicks quickly.
var images = [
'http://i.stack.imgur.com/uClcV.jpg?s=328&g=1',
'https://www.gravatar.com/avatar/d050da3cf82fdf6cfa431358fee9a397?s=128&d=identicon&r=PG&f=1',
'https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=128&d=identicon&r=PG'
];
var current = 0;
updateImage(images[current], images[current]);
function updateImage(image, title) {
var img = $('#image');
img.stop(true, true).fadeOut('fast', function() {
img.find('a').attr('href', image).attr('title', title);
img.find('img').attr('src', image);
img.fadeIn('fast');
});
}
$("#next").click(function() {
current = (current + 1) % images.length;
updateImage(images[current], images[current]);
});
<input type="button" id="next" value="Next">
<div id="image">
<a>
<img style="height: 128px; width: 128px"><!-- Never do that, but for a demo, it's okay -->
</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Is expected result that #slider not fade to appearance of empty
background during image transitions ?
Fades to either white, ready for the new image to fade in, or a crossfade - either would be acceptable
Try setting #slider width , height to expected img width, height; setting background-color to #000
css
#slider {
width:500px;
height:505px;
background-color:#000;
}
js
//clicking thumbnails
$(".image").click(function () {
var image = $(this).attr("rel"); //getting the rel tag from the a tag
var title = $(this).attr("data-title"); //data title from a tag
$('#image').fadeOut('fast', function() { //fades out last image
$('#image').html('<a href="' + image + '" data-lightbox="image-1" data-title="' + title + '">'
+ '<img src="' + image + '" class="image"/></a>')
.fadeIn('fast');
})
jsfiddle http://jsfiddle.net/bmu43fm7/13/

Jquery image alt on hover

I have one question about image alt on hover image.
I have to create this fiddle
In this fiddle you can see there are big and smole images. When you hoverover smole image then big image changing.
What i want to do. I want to add a alt from big image. In my demo shows alt with only smole images. Also my code said undefined. What i need to do for showing alt only from big images.
$(document).ready(function() {
var a = $(this).attr('alt');
$("#magazin_sldwr li img").hover(function(){
clearTimeout(autoScrollerTimer);
$(this).parent('li').addClass('active').siblings().removeClass('active');
$('#mainm-img').attr('src',$(this).attr('src').replace('thumb/', '')).parent().attr('href',$(this).parent().attr('href'),$(this).parent().append('<div class="title">' + a + '</div>'));
}, function(){
autoChangeImage();
});
For the undefined problem:
You're setting the variable a to $(this).attr('alt') too early, before $(this) is the thumbnail.
Try setting it in the function you pass to hover(), like so:
$(document).ready(function() {
var a;
$("#magazin_sldwr li img").hover(function(){
a = $(this).attr('alt');
clearTimeout(autoScrollerTimer);
$(this).parent('li').addClass('active').siblings().removeClass('active');
$('#mainm-img').attr('src',$(this).attr('src').replace('thumb/', '')).parent().attr('href',$(this).parent().attr('href'),$(this).parent().append('<div class="title">' + a + '</div>'));
}, function(){
autoChangeImage();
});
For showing the other alt text, you'll have to be more detailed in your question.

Load various size images in a fancybox

I have 5-6 images with various sizes like width from 1000px to 1048px and height from 593px to 1736px. But its not loading small images. I tried to pass the width & height but its not working.
HTML
<a class="fancybox" href="images/press/creating websies for NGOS.png" data-fancybox-group="gallery" title="Creating websites for NGOs" data-width="1048" data-height="593">
<img src="images/press/creating websies for NGOS.png" style="border:0" alt="">
</a>
JQUERY
$(".fancybox").fancybox({
beforeShow: function () {
this.width = $(this.element).data("width");
this.height = $(this.element).data("height");
}
});
So how do it. It will load as per the width & height passed from html. Any idea guys ?
The Problem
Your current URL is
http://firstplanet.in/about/feature.php/
and your images are linked to
images/press/commitment to unemployment.png
which gets expanded to
http://firstplanet.in/about/feature.php/images/press/creating%20websies%20for%20NGOS.png
change your image links to
/about/images/press/commitment to unemployment.png
to get them working.
More Info
Read this article on relative URLs. Here is an excerpt.
Not prepending a /
If the image has the same host and the same path as the base document:
http://www.colliope.com/birdpics/owl/pic01.jpg
http://www.colliope.com/birdpics/owl/page.html
We would write < img src="pic01.jpg" >
Prepending a /
If the image has the same host but a different path:
http://www.colliope.com/gifs/groovy14/button.gif
http://www.colliope.com/birdpics/owl/page.html
We would write < img src="/gifs/groovy14/button.gif" >
Part of the problem is the context of this being lost.
Whenever we use this in a function, the context of this takes that function.
So we can assign it early : var $this = $(this);
Edit: Perhaps this.element is a fancybox way to get the element, I don't know, if so, I'm wrong. Nontheless, here's what we can do , if you want to make use of those data height and width attributes:
$('a.fancybox').on('click', function (e) {
e.preventDefault(); /* stop the default anchor click */
var $this = $(this); /* register this */
$.fancybox({
'content': $this.html(), /* the image in the markup */
'width': $this.attr("data-width"),
'height': $this.attr("data-height"),
'autoDimensions': false,
'autoSize': false
});
});
Try this out here
Also some CSS will help keep the fancybox frame from scrolling ( for this direct image usage )
.fancybox-inner img {
display:block;
width:100%;
height:100%;
}
Try
$.fancybox("<img src='images/press/creating_websies_for_NGOS.png' style='border:0'>");

Categories

Resources