Using HTML data-attribute to set CSS background-image url - css

I plan on building a custom photo gallery for a friend and I know exactly how I am going to be producing the HTML, however I am running into a small issue with the CSS.(I would prefer to not have the page styling rely on jQuery if possible)
My question regards:
Data-Attribute in HTML
Background-image in CSS
I am using this format for my html thumbnails:
<div class="thumb" data-image-src="images/img.jpg"></div>
and I assume the CSS should look something like this:
.thumb {
width:150px;
height:150px;
background-position:center center;
overflow:hidden;
border:1px solid black;
background-image: attr(data-image-src);/*This is the question piece*/
}
My goal is to take the data-image-src from the div.thumb in my HTML file and use it for each div.thumb(s) background-image source in my CSS file.
Here is a Codepen Pen in order to get a dynamic example of what I am looking for:
http://codepen.io/thestevekelzer/pen/rEDJv

You will eventually be able to use
background-image: attr(data-image-src url);
but that is not implemented anywhere yet to my knowledge. In the above, url is an optional "type-or-unit" parameter to attr(). See https://drafts.csswg.org/css-values/#attr-notation.

If you wanted to keep it with just HTML and CSS you can use CSS Variables.
Keep in mind, css variables aren't supported in IE.
<div class="thumb" style="--background: url('images/img.jpg')"></div>
.thumb {
background-image: var(--background);
}
Codepen: https://codepen.io/bruce13/pen/bJdoZW

It is not best practise to mix up content with style, but a solution could be
<div class="thumb" style="background-image: url('images/img.jpg')"></div>

You will need a little JavaScript for that:
var list = document.getElementsByClassName('thumb');
for (var i = 0; i < list.length; i++) {
var src = list[i].getAttribute('data-image-src');
list[i].style.backgroundImage="url('" + src + "')";
}
Wrap that in <script> tags at the bottom just before the </body> tag or wrap in a function that you call once the page loaded.

How about using some Sass? Here's what I did to achieve something like this (although note that you have to create a Sass list for each of the data-attributes).
/*
Iterate over list and use "data-social" to put in the appropriate background-image.
*/
$social: "fb", "twitter", "youtube";
#each $i in $social {
[data-social="#{$i}"] {
background: url('#{$image-path}/icons/#{$i}.svg') no-repeat 0 0;
background-size: cover; // Only seems to work if placed below background property
}
}
Essentially, you list all of your data attribute values. Then use Sass #each to iterate through and select all the data-attributes in the HTML. Then, bring in the iterator variable and have it match up to a filename.
Anyway, as I said, you have to list all of the values, then make sure that your filenames incorporate the values in your list.

HTML
<div class="thumb" data-image-src="img/image.png">
jQuery
$( ".thumb" ).each(function() {
var attr = $(this).attr('data-image-src');
if (typeof attr !== typeof undefined && attr !== false) {
$(this).css('background', 'url('+attr+')');
}
});
Demo on JSFiddle
You could do this also with JavaScript.

For those who want a dumb down answer like me
Something like how to steps as 1, 2, 3
Here it is what I did
First create the HTML markup
<div class="thumb" data-image-src="images/img.jpg"></div>
Then before your ending body tag, add this script
I included the ending body on the code below as an example
So becareful when you copy
<script>
var list = document.getElementsByClassName('thumb');
for (var i = 0; i < list.length; i++) {
var src = list[i].getAttribute('data-image-src');
list[i].style.backgroundImage="url('" + src + "')";
}
</script>
</body>

Here is simple example using jQuery we can put the images in background
$('*[data-background-image]').each(function() {
$(this).css({
'background-image': 'url(' + $(this).data('background-image') + ')'
});
});
div{
height:200px;
width:100% ;
background-size: cover;
background-position: center center;
background-repeat: no-repeat;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-background-image="https://via.placeholder.com/500"> </div>

HTML CODE
<div id="borderLoader" data-height="230px" data-color="lightgrey" data-
width="230px" data-image="https://fiverr- res.cloudinary.com/t_profile_thumb,q_auto,f_auto/attachments/profile/photo/a54f24b2ab6f377ea269863cbf556c12-619447411516923848661/913d6cc9-3d3c-4884-ac6e-4c2d58ee4d6a.jpg">
</div>
JS CODE
var dataValue, dataSet,key;
dataValue = document.getElementById('borderLoader');
//data set contains all the dataset that you are to style the shape;
dataSet ={
"height":dataValue.dataset.height,
"width":dataValue.dataset.width,
"color":dataValue.dataset.color,
"imageBg":dataValue.dataset.image
};
dataValue.style.height = dataSet.height;
dataValue.style.width = dataSet.width;
dataValue.style.background = "#f3f3f3 url("+dataSet.imageBg+") no-repeat
center";

Related

how to set the different background image format (png and webp) of the same image in section tag

I have started using webp images in my site with <picture> tag. all set except this
<section class="sec-bg" style="background: url('images/bg.jpg');">
I don't know, how to set the different background image format (png and webp) of the same image. please give a solution for this inline CSS in the section tag.
for other images, I'm using below code
<picture>
<source srcset="img/awesomeWebPImage.webp" type="image/webp">
<source srcset="img/creakyOldJPEG.jpg" type="image/jpeg">
<img src="img/creakyOldJPEG.jpg" alt="Alt Text!">
</picture>
I would suggest you to use JS to handle that issue. For example you can find all elements with background or background-image style on a page and after that just replace your webp image to jpeg version. So your script will look like:
document.deepCss= function(who, css){
if(!who || !who.style) return '';
var sty= css.replace(/\-([a-z])/g, function(a, b){
return b.toUpperCase();
});
if(who.currentStyle){
return who.style[sty] || who.currentStyle[sty] || '';
}
var dv= document.defaultView || window;
return who.style[sty] ||
dv.getComputedStyle(who,"").getPropertyValue(css) || '';
};
var elms = document.getElementsByTagName('*');
for (var i=0;i<elms.length;i++) {
var url = document.deepCss(elms[i], 'background-image');
if (url) {
url=/url\(['"]?([^")]+)/.exec(url);
if (url && url[1]) {
elms[i].style.backgroundImage = "url("+url.replace('.webp', '.jpeg')+")"
}
}
}
It would be much easier for you to store the same image in two formats with the same name, for example test.jepg and test.webp, in this case you can just replace image extension by using the script which I provided above.
If you don't want to use JavaScript to serve formats specific to the client consider using the <picture> tag with both sources and using CSS and position: absolute and z-index: -1 to push the image into the background.
To expand your example, here's how it would work:
HTML
<div class="sec-bg">
<div class="sec-bg__image">
<picture>
<source srcset="img/awesomeWebPImage.webp" type="image/webp">
<source srcset="img/creakyOldJPEG.jpg" type="image/jpeg">
<img src="img/creakyOldJPEG.jpg" alt="Alt Text!">
</picture>
</div>
<div class="sec-bg__content">
<p>Your section content goes here!</p>
</div>
</div>
CSS
.sec-bg
{
position: relative;
z-index: 0;
}
.sec-bg__image
{
position:absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-indez: -1;
}
we can use image-set attr
.box {
background-image: -webkit-image-set(
url("large-balloons.avif") type("image/avif"),
url("large-balloons.jpg") type("image/jpeg"));
background-image: image-set(
url("large-balloons.avif") type("image/avif"),
url("large-balloons.jpg") type("image/jpeg"));
}
refer to it
https://developer.mozilla.org/en-US/docs/Web/CSS/image/image-set#using_image-set_to_provide_alternative_image_formats
Have you tried the CSS rule below ?
background-image: url('img/image1.webp'), url('img/image1.jpg');
Considering that both images are the same, the second one will be used if the first one doesn't exist. This way, it acts like a "fallback image".
An inline solution can be
<section class="sec-bg" style="background-image: url('img/image1.webp'), url('img/image1.jpg');">

Lay a .png image partially over (on top of) menu

I have an accordion menu that I have tweaked to suit my needs. My last stumbling block is that I have an image (see attached image) of a FedEx Courier that I need to lay on top of the menu and yet still allow users to click through it to activate (access) the accordion menu. The image is a separate image that is set to the desired alpha as created in Photoshop. The file is merely a snapshot of how it would look if it was the way I wanted it.
If this is even possible, what code would I use and exactly where would I place it? If in the CSS file, where does it go and between which lines?
Original full size Image file
You can apply the css:
pointer-events: none;
to the image above the links.
See fiddle https://jsfiddle.net/4zgcrkyz/
pointer-events: none; is a suitable solution if you do not need to care about IE < 11. More info on compatibility here.
Alternatively you can use elementFromPoint() which has compatibility IE > 5.5
The following trick allow you to select under your cover image without using pointer-events: none;
https://jsbin.com/tuhotagize/edit?html,output
Explanation:
At click on cover image.
Hide cover image temporary.
Get mouse coordinates.
Get HTML element under that mouse coordinates (so you know what under the cover).
Trigger click event on that HTML element.
Show cover image again.
Another alternative solution to your problem, which does not include any JS is:
Trim your image in PhotoShop as should appear inside the menu. Use CSS background-image property on it
Use the courier FedEx image only as CSS background-image the body of your page.
You can achieve the same visual effect using only CSS.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test</title>
<style>
img {
position: absolute;
top: 0;
left: 0;
opacity: 0.4;
}
a {
display: block;
width: 300px;
height: 20px;
background-color: greenyellow;
}
a:hover {
background-color: #FF0000;
}
</style>
<script>
window.app = {
show: function () {
document.getElementById('cover').style.display = '';
},
hide: function () {
document.getElementById('cover').style.display = 'none';
},
event: null,
start: function () {
document.getElementById('cover').addEventListener('click', function (event) {
this.hide();
this.event = event;
var target = document.elementFromPoint(event.pageX, event.pageY);
this.show();
target.click();
}.bind(this));
var links = document.querySelectorAll('a');
for (var i = 0, len = links.length; i < len; i++) {
links[i].addEventListener('click', function (event) {
alert('click on ' + event.target.id);
}.bind(this));
}
}
};
</script>
</head>
<body onload="window.app.start();">
<img id="cover" src="http://placehold.it/200x200" />
<a id="a1">link</a>
<a id="a2">link</a>
<a id="a3">link</a>
<a id="a4">link</a>
<a id="a4">link</a>
<a id="a6">link</a>
</body>
</html>

How to have an anim gif on a link and play it on hover and reset

First of all many thanks for this page, it has been helping me a lot! But at this point I have a question where I cannot find an answer that fits what I want (maybe it cannot be achieved the way I am doing it).
I want to have a link with a static image, and when the user moves the cursor over the link I want an animated gif to play (the anim gif is set to not loop, so it only plays once). And when the user moves out go back to the static image and if the user goes in again, the gif should play again from the beginning.
I am using html5 combined with CSS to create my web (which I am using to learn at the same time). I did programing in the past with C++ and similar, but never on a web context.
So far this is what I tried:
CSS:
.img-acu
{
float: left;
width: 450px;
height: 264px;
background:transparent url("acu.gif") center top no-repeat;
}
.img-acu:hover
{
background-image: url("acusel.gif");
}
HTML:
But nothing at all appears :(
The weird thing is, I used this same example with two static images (png format) and it worked fine, but for some reason with the animated gif it doesn't want to work.
The I tried this:
CSS:
#test
{
width: 450px;
height: 264px;
background-image: url("acu.gif");
background-repeat: no-repeat;
background-position: left;
margin-left: 75px;
}
#test:hover
{
background-image: url("acusel.gif");
}
HTML:
<div id="test"></div>
And that works perfectly, it is just the link doesn't work and when the animated gif reaches the last frame, it never resets (unless I reload the page).
Do you know if there is any way to achieve this properly in HTML5 + CSS? should I use javascript or php?
I would really appreciate any help!
Thanks a lot!!
That can be achieved by use a static image and your gif image(Hey, that how 9gag do it!)
A basic script could be somthing like that:
<img id="myImg" src="staticImg.png" />
<script>
$(function() {
$("#myImg").hover(
function() {
$(this).attr("src", "animatedImg.gif");
},
function() {
$(this).attr("src", "staticImg.jpg");
}
);
});
</script>
Hopefully this simple way can help someone:
<img class="static" src="https://lh4.googleusercontent.com/-gZiu96oTuu4/Uag5oWLQHfI/AAAAAAAABSE/pl1W8n91hH0/w140-h165-no/Homer-Static.png"><img class="active" src="https://lh4.googleusercontent.com/i1RprwcvxhbN2TAMunNxS4RiNVT0DvlD9FNQCvPFuJ0=w140-h165-no">
Then add the following CSS:
.static {
position: absolute;
background: white;
}
.static:hover {
opacity: 0;
}
This should hopefully help some people. I got the code from a codepen and decided some stack overflow users may find it helpful. If you would like to view the original codepen, visit here: CodePen
The approach you took did not work because CSS will not change the background on < a >. Solving this can be done entirely with vanilla JS + HTML. The trick is to place:
<div class="img-acu">
inside of:
(insert here)
All that's left is to have CSS target the div. That way, you can set the static background, which then changes on :hover
Here's a fiddle showing this in action (or you can fiddle with this: https://jsfiddle.net/lyfthis/yfmhd1xL/):
.img-acu
{
float: left;
width: 250px;
height: 132px;
background:transparent url("https://i.imgur.com/7r91PY3.jpeg") center top no-repeat;
background-size: 125%;
}
.img-acu:hover
{
background-image: url("https://media.giphy.com/media/QMkPpxPDYY0fu/giphy.gif");
}
<!-- Don't do this:
-->
<div>
<div>Click on image below to go to link:</div>
<a href="https://www.google.com" title="ACU Project link">
<div class="img-acu"></div>
</a>
</div>
Try this if you are OK to use canvas:
<!DOCTYPE html>
<html>
<head>
<style>
.wrapper {position:absolute; z-index:2;width:400px;height:328px;background-color: transparent;}
.canvas {position:absolute;z-index:1;}
.gif {position:absolute;z-index:0;}
.hide {display:none;}
</style>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script>
window.onload = function() {
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var img = document.getElementById("gif");
ctx.drawImage(img, 0, 0);
}
$(document).ready(function() {
$("#wrapper").bind("mouseenter mouseleave", function(e) {
$("#canvas").toggleClass("hide");
});
});
</script>
</head>
<body>
<div>
<img id="gif" class="gif" src="https://www.macobserver.com/imgs/tips/20131206_Pooh_GIF.gif">
<canvas id="canvas" class="canvas" width="400px" height="328px">
Your browser does not support the HTML5 canvas tag.
</canvas>
<div id="wrapper" class="wrapper"></div>
</div>
</body>
</html>

How to align text and image in xslt with css

Hi I have an xml file in wich I put some image in this way: <pb facs="ciao.jpg">.
Then I have an xsl file where i put a Java script like this:
<script type="text/javascript">
function toggleSize(img){
if (parseInt(img.style.width) !=220){
img.style.width='220px';
}
else {
img.style.width = '90%';
}
}
function showHideNote(noteId){
var note = document.getElementById(noteId);
if (note.className == 'hiddenNote') {
note.className='showingNote';
}
else {
note.className='hiddenNote';
}
return false;
}
</script>
and it makes a little image where I can click and all the text under.
So the problem is that I would like to have a bigger image on the left and the text related on the right. Any suggestion?
Just add float: left to the style for the image.
<div>
<h1 style="text-align:center" id="chapter_1">Capitulo primeyro</h1>
<img src="folio16r.jpg" style="width: 120px; cursor: pointer; float: left"
onclick="toggleSize(this)" alt="page image from manuscript">
<p style="text-align:justify; font-family:garamond"> dddd </p>
</div>
By the way, the html you posted in the comment is not the same as the original question (the question has ciao.jpg for the picture, while the HTML has folio16r.jpg. And I'm not sure how and where you're appying the style. So I hope you can make this work.

How to remove div backgrounds?

I have an div element in website markup as follows.
<div id="mainContainer" class="container" runat="server">
I have assigned it a css class as follows.
div#mainContainer.container {
width: 100%;
margin: 0 auto;
margin-top:40px;
height:500px;
background:url("../img/bgimg.png")no-repeat;
}
Now after a button click I want to remove only the background of that div and don't want to tamper any positioning of elements inside it. And btw I am using ASP.net to create this website. How can I do that ?
If you want to achieve this in a server-side event, you'll need to add the runat="server" attribute to your <div> element, and it will need an id attribute. This will make it easy to alter server-side.
You'll need an event-handler method in your code-behind for the button click.
In this event handler, do something like (this assumes the id of your <div> is "container")
container.Style["background"] = String.Empty;
However, in your question, you say you've assigned your element a class. If this is the case, the above might not work. It might be easiest to define another CSS class without this background image rule, and then in the code-behind do this:
container.Attributes["class"] = "newClass";
Now with pure CSS.
.button{
background:green;
}
.background-class{
background:red;
}
.button:active + .background-class{
background:yellow;
}
Check this http://jsfiddle.net/AX8tY/
You will need to use JavaScript (either direct or some JavaScript framework like jQuery) and set the CSS style to
background:none
This means you could alter the style of the specific instance or you could define a new CSS class to apply.
With a simple javascript as:
onclick="javascript:getElementById('div_element_id').style.backgroundImage = '';"
or you may use jQuery's API aswell.
How about something like this:
If your HTML is something like this:
<button class="your-button" />
<div class="background-class">
...
</div>
Then your JS might look something like this (this assumes you're also using jQuery):
$(".your-button").click(function(){
$(".background-class").removeClass("background-class");
});
EDIT : I just saw in your comment that you'd like to use a server-side event. This is a client-side solution.
If you use jQuery you could try something like this :
$('button#idButton').click(function{
$('div#idDiv').css('background':'none')
});
If you don't use jquery you should implement a javascript function on the onClick event, try something like :
<input type="button" name="button1" id="button1" onClick="javascript:deleteBackground()" />
<script>
function deleteBackground(){
Document.getElementById('div_element_id').style.backgroundImage = '';
}
</script>
if you defined a class
.yourclassname {
background: url('..');
}
you can also use the remove class function
$('div').removeClass('yourclassname');
<script language="javascript" type="text/javascript">
function SetClass() {
var ID = document.getElementById('<%=mainContainer.ClientID %>');
ID.className += " ChangeBackground";
return false;
}
</script>
<style type="text/css">
div#mainContainer.container
{
width: 100%;
margin: 0 auto;
margin-top: 40px;
height: 500px;
background: url("wallpaper-1554220.jpg")no-repeat;
}
.ChangeBackground
{
background: none !important;
}
</style>
<asp:Button ID="btn" OnClientClick="return SetClass();" runat="server" Text="Change CSS"/>

Resources