BG Images WITHOUT Defining Them In CSS

Size
5,580 Kb
Views
16,192

How do I make an bg images without defining them in css?

A short jQuery snippet that will let you set resolution specific background images using data attributes in your HTML instead of writing styles and media queries in CSS.. What is a bg images without defining them in css? How do you make a bg images without defining them in css? This script and codes were developed by Brandon Kennedy on 18 September 2022, Sunday.

BG Images WITHOUT Defining Them In CSS Previews

BG Images WITHOUT Defining Them In CSS - Script Codes HTML Codes

<!DOCTYPE html>
<html >
<head> <meta charset="UTF-8"> <title>BG Images WITHOUT Defining Them In CSS</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css"> <link rel="stylesheet" href="css/style.css">
</head>
<body> <h2> <span>Set Background Images</span> <span>Based on Pixel Ratio</span> <span>WITHOUT</span> <span>Media Queries or CSS</span>
</h2>
<div data-src="http://placehold.it/400x400"> This has only a data-src with the 1x image path.
</div>
<div data-src="http://placehold.it/400x400" data-srcset="http://placehold.it/400x400 1x"> This has a data-src and a data-srcset, both with just the 1x image path.
</div>
<div data-src="http://placehold.it/400x400" data-srcset="http://placehold.it/400x400 1x, http://placehold.it/800x800 2x"> This has a data-src with the 1x image path and a data-srcset with both the 1x and 2x image paths.
</div>
<div data-src="http://placehold.it/400x400" data-srcset="http://placehold.it/400x400 1x, http://placehold.it/800x800 2x, http://placehold.it/1200x1200 4x"> This has a data-src with the 1x image path and a data-srcset with both the 1x, 2x, and 3x image paths.
</div> <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> <script src="js/index.js"></script>
</body>
</html>

BG Images WITHOUT Defining Them In CSS - Script Codes CSS Codes

/***********************************************************
*
* everything in here is just to make the pen look nice.
* absolutely NONE of it affects the functionaility of what
* i'm showing off in the JS.
*
***********************************************************/
*, *:before, *:after { box-sizing: border-box;
}
*, *:focus, *:active, *:focus:active, *:before, *:before:focus, *:before:active, *:before:focus:active, *:after, *:after:focus, *:after:active, *:after:focus:active { outline: none;
}
body { background: -webkit-linear-gradient(325deg, mediumspringgreen, dodgerblue); background: linear-gradient(-235deg, mediumspringgreen, dodgerblue); color: white; margin: 0 auto; padding: 20px; width: 380px;
}
div { box-shadow: 0 2px 8px -3px black; font-size: 1.1em; margin: 0 auto; margin-bottom: 20px; min-height: 200px; padding: 20px; text-align: center;
}
h2 { font-family: Arial; text-align: center;
}
h2 span { display: block;
}
h2 span:nth-child(1) { font-size: 1.24em;
}
h2 span:nth-child(2) { font-size: 1.43em;
}
h2 span:nth-child(3) { font-size: 3em;
}
h2 span:nth-child(4) { font-size: 1.34em;
}

BG Images WITHOUT Defining Them In CSS - Script Codes JS Codes

// the code detailed here is a small piece of a much larger
// jQuery plugin originally written by a coworker of mine
// named Aaron Benton (https://github.com/bentonam). my
// attempts to simplify it... failed. aparently he knows
// what he is doing...
//
// but his documentation sucked so hopefully this is easier
// for you to understand than it was for me to figure out.
//
$(document).on('ready pageready', function() { // first we find our elements that we want to apply a // background image to. we'll identify them by the // data-src attribute because that is the very least // that is required for this to work. var elements = $('[data-src]'); // now we need to loop through all of the elements we just // collected. for (var i = 0; i < elements.length; i++) { // we need to get our image sources from the data // attributes. // // for each element, we need to get the src path of // the image. remember this is always there so it is // pretty straight forward. var img_src = $(elements[i]).data('src'), // then we need to check for srcset info. if you // aren't familiar with the srcset attribute then // shame on you (...kidding). but look it up, its // super great. for the purpose of this // documentation, all you need to know is that it // handles your image resolution. and by looking at // the syntax in the HTML pane, you can probably // figure out how. anyway, we need to get it and // again, its pretty straight forward. img_srcset = $(elements[i]).data('srcset'); // now we're going to assign the image as the background // with some good old fashion CSS!! // // but if we're using the srcset option, we still don't // know what that image is. so we're going to call this // fancy mediaImage function that we wrote down below // and it is going to return our image path. $(elements[i]).css({ // so we set the background. background: 'url(' + mediaImage(img_srcset || img_src) + ') no-repeat center/cover' // and here is a breakdown of why i did it this way: // // - specifically set the 'background' and not just // the 'background-image' because we also want to set // other things to ensure that some arbitrary styles // somewhere don't screw with our background. you // don't have to do it this way (obviously) but i // build these things for other people to use and i // try to make it as difficult as possible for rogue // developers to mess it up. // // - i throw the 'no-repeat' on there so the image // doesn't, well... repeat. // // - the 'center/cover' will ensure that our image is // centered and stretched to always fit the container. // i do this because there are times when the people // responsible for making the images and the people // who are actually coding them aren't always on the // same page with sizes... even if those people are // really the same person. }); } // now lets get into this mediaImage function thing that // will return the proper image when data-srcset is used function mediaImage(resolutions) { // first we need to use an immediately invoked // function expression (iife) to set up an object // of the available resolution images. you can read // more about these here // http://benalman.com/news/2010/11/immediately-invoked-function-expression/ // but for the time being lets just accept that it // is necessary. var sets = (function() { // now we make sure that we always have a 1x // defined, even if the value is null. var res = { '1x': '' }; // now, we take the value of data-srcset that we sent // in and break it into an array at each ','. then we // loop off that array. resolutions.split(',').forEach(function(v) { // we trim each value to remove the leading space // that is probably there on everything that came // after a comma. then we split it again. this time // at the ' ', leaving us with an array that has an // image path in the first position and that image's // intended screen resolution in the second. var item = $.trim(v).split(' '); // now this line gets a little confusing. ultimately // it is just assigning the image path to the // appropriate resolution in our 'res' object. but // there are some extra bits to ensure you get // correct values applied to the correct keys. so // lets break it down step by step: // // first we know we're setting something in 'res' to have a value of the image path. so we start with this: // // res[???] = item[0]; // // now we want to make sure we are only working with // a vaild srcset option, which we split into an // array so that it should only ever have 2 // positions. so if it is valid, we want to use the // second position as our res key, otherwise we just // override the '1x' value: // // res[item.length === 2 ? item[1] : '1x'] = item[0]; // // but just to be safe, we're also going to throw a // regex test at the second position to make sure it // is a number followed by the letter 'x', resulting // in this final code. res[/[0-9]x$/.test(item[1]) && item.length === 2 ? item[1] : '1x'] = item[0]; }); // at the end of the loop, we return the 'res' object // which, because of our iife thing, effectively // assigns it to the 'sets' variable. return res; })(); // we need to know which key of the 'sets' (formerly // 'res') object we should return as the result of the // mediaImage function. but to get the appropriate key // for our device, we need to know our device's pixel // ratio. we get that using... window.devicePixelRatio. // and we throw in a fall back of 1 just in case. then // we'll use Math.ceil() function to round up to the // nearest integer. and we throw an 'x' on the end // because it has to match up with our keys. finally, we // add an '||' to provide a default of '1x' because we // made sure it would always exist. return sets[Math.ceil(window.devicePixelRatio || 1) + 'x'] || sets['1x']; };
});
BG Images WITHOUT Defining Them In CSS - Script Codes
BG Images WITHOUT Defining Them In CSS - Script Codes
Home Page Home
Developer Brandon Kennedy
Username brandonkennedy
Uploaded September 18, 2022
Rating 4
Size 5,580 Kb
Views 16,192
Do you need developer help for BG Images WITHOUT Defining Them In CSS?

Find the perfect freelance services for your business! Fiverr's mission is to change how the world works together. Fiverr connects businesses with freelancers offering digital services in 500+ categories. Find Developer!

Brandon Kennedy (brandonkennedy) Script Codes
Create amazing video scripts with AI!

Jasper is the AI Content Generator that helps you and your team break through creative blocks to create amazing, original content 10X faster. Discover all the ways the Jasper AI Content Platform can help streamline your creative workflows. Start For Free!