CSS3: set background image to rel attribute value - css

I'm looking to set the background-image (or even render an image via the pseudo elements :after or :before) to the value, which will be a URL, of a rel attribute, but only in certain cases (this is a cloud file listing). For example:
HTML:
<div class="icon ${fileExtension}" rel="${fileURL}"></div>
It would be great if I could do something like this:
CSS:
.icon.png,
.icon.jpg,
.icon.jpeg,
.icon.bmp,
.icon.gif { background-image: attr(rel,url); }
... but obviously that doesn't work as, if I'm not mistaken, the attr() CSS function only works inside pseudo element blocks.
I know there are ways of doing this using conditional JSP or even jQuery logic, but I'd like to figure out a neat way of doing it via CSS3, since I'm only concerned with modern browsers at the moment anyway.
Also, I don't want to explicitly set the background image to the URL or create an <img> element, because by default if the file is not a supported image, I'd rather display a predetermined set of icons.

Using
.icon:after{ content: ""attr(rel)""; }
displays the rel value as text.
A jQuery solution is to add the background-image (taken from the rel value) as inline CSS:
jQuery(function($) {
$('.icon').each(function() {
var $this = $(this);
$this.css('background-image', 'url(' + $this.attr('rel') + ')');
});
});

I've tried to do something using jQuery but i don't exactly understand what you want so i can't go on with my code. So far i've done only this.
EDITED I hope it's exactly what you need
$(function(){
var terms = new Array('png','jpg','jpeg','bmp','gif');
$('.icon').each(function(){
var t = $(this),
rel = t.attr('rel'),
cls = t.attr('class');
cls = cls.split(' ');
for (var i=0; i < terms.length; i++) {
if (terms[i] == cls[1]) {
t.css('background-image','url('+rel+')');
}
}
});
});
if you can give me a better example, to undestand exactly what you want, i hope somebody from here will be able to solve your problem.
Regards,
Stefan

I've decided to go the jQuery route, and used a combination of #ryanve and #stefanz answers. Thanks guys
$(document).ready(function() {
$(".png,.jpg,.jpeg,.bmp,.gif,.tiff").each(function(n) {
var bg = 'url(' + $(this).attr("rel") + ')';
$(this).css('background-image', bg);
});
});
I think this is relatively neat/concise and works well for my needs. Feel free to comment on efficiency, methodology, etc.

Related

if image width > 400 = image width = 100% css

I'd like to check if an image width has more than 400px I'd like this image to get full div width. if image is less than 400px just print it in its normal size.
any ideas how to do this?
<div id="volta">
<img src="/img/volta.jpg">
</div>
#volta{
width:500px;
}
As far as I know, this does not exist in CSS. What you should do instead is use classes.
Define some CSS class that applies the styles you want:
.long_width {
background: blue;
}
Then you would use Javascript to check the width of the image. You don't need jQuery to do this you can do it in vanilla Javascript (unless you already have jQuery imported and need it for other things). Maybe something like this:
let elm = document.querySelector('[src="/img/volta.jpg]"');
let width = window.getComputedStyle(elm).getPropertyValue('width');
And then you would use Javascript to add and remove styles accordingly:
if (width > 400) {
elm.classList.add("long_width");
}
else {
elm.classList.remove("long_width");
}
The specific answer to your question depends on what your intentions are. But to keep your code simple, you should use Javascript to handle the logic and not depend on CSS selectors for things this complicated. Instead, create a CSS class that contains the styles you need, and then use Javascript to apply it based on the size of the user uploaded image.
Additionally, if the user uploads the image, you should load it into memory and check its attributes in memory rather than by depending on a DOM element. Something like:
let img = new Image();
img.src = "{data URL of img}"
You will need javascript / jQuery to work. Something like this:
$('img').each(function(){
if($(this).width() > 400){
$(this).css('width', '100%');
}
});
Here is also working jquery example.
Apply an id to the image, and with jquery check its width
If it is greather than 400px modify his width or add a class that does the same.
Example
$(document).ready(function(){
if($("#image").width() > 400){
$("#image").css("width", "100%");
}
else{
$("#image").css("width", "10px");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id = "image" src = "https://pm1.narvii.com/6919/98f453834b5d87a6c92118da9c24fe98e1784f6ar1-637-358v2_hq.jpg"/>
You can do it like FlokiTheFisherman (with %), or you can use "wv" instead of "%".
I recommend using vw.
img[width='400'] {
width: 100%;
}

Modifying jQuery selector for cross browser grayscale filter

Looking to use this cross browser grayscale filter and had it working on all images, but I want to restrict the effect to the images within a single div.
In function.js I changed all instances of the selector from grayscale($('img'));
to grayscale($('#grayscale-div img')); and did so in all instances. It's adding the CSS class, but in IE11 the effect doesn't work anymore.
I'm trying to see if this is a mistake I'm making with the jQuery selector. Thanks for in advance for pointing me in the right direction.
Code Excerpt:
if (getInternetExplorerVersion() >= 10){
$('#grayscale-div img').each(function(){
var el = $(this);
el.css({"position":"absolute"}).wrap("<div class='img_wrapper' style='display: inline-block'>").clone().addClass('img_grayscale').css({"position":"absolute","z-index":"5","opacity":"0"}).insertBefore(el).queue(function(){
var el = $(this);
el.parent().css({"width":this.width,"height":this.height});
el.dequeue();
});
this.src = grayscaleIE10(this.src);
});
// Quick animation on IE10+
$('#grayscale-div img').hover(
function () {
$(this).parent().find('img:first').stop().animate({opacity:1}, 200);
},
function () {
$('.img_grayscale').stop().animate({opacity:0}, 200);
}
);
The getInternetExplorerVersion() conditional check is failing in IE11. The following change:
if(getInternetExplorerVersion() >= 10 || !!window.MSInputMethodContext)
will fix it in the code shown above. Here are some unrelated questions which explain the problem and the solution:
How to detect IE11?
Detecting IE11 using CSS Capability/Feature Detection

Using Css to Clear TextBox Text/value

I was wondering, if it was possible to clear a text box with a css code rather than using javascript ?
This isn't possible with CSS, only with JS:
Event handler function:
addEvent(document.getElementById('IDHERE'), "focus",
function() {
clearText('IDHERE');
});
Event listener function:
//addEvent listener
function addEvent(obj, type, fn) {
if (obj.addEventListener) {
obj.addEventListener(type, fn, false);
} else {
if (obj.attachEvent) {
obj["e" + type + fn] = fn;
obj[type + fn] = function() {
obj["e" + type + fn](window.event);
};
obj.attachEvent("on" + type, obj[type + fn]);
}
}
}
ClearText function:
//Clear on focus function
function clearText(id) {
document.getElementById(id).value = "";
}
This is pure JS, no libraries needed here, very fast and x-browser compatible :)
You cannot use CSS to manipulate the DOM. In other words: this is not possible.
With CSS one cannot change a document, only the look and behaviour of the document but that's it.
This is impossible. CSS is for presentation only, HTML is for the information and structure and javascript is for DOM manipulation. You will have to use Javascript or one of its libraries to do this :)
can be done, but just in a visual way, it wont actually go, but wont be shown too
there can be many tricks, one can be to set the text color same as the background of your text box, disable selection.
but if you want it to be completely gone you need to use javascript

css not class select?

Theres a mistake in my rather large demo where i assume all the divs under the class special will be used to align something. Now i realize i need to add an extra div outside of the part i want to align but inside of .special.
How do i write .special div[NOT someclass] ? or is there no way to do this and i need to rewrite a lot of html?
CSS3 includes the not() selector. The only problem is (you guessed it) no IE compatibility. If you're willing to require Javascript from IE <9 users, you can get IE compatibility with IE9.js.
+1 to both answers above.
I'll add i was able to get away with some things but writing this in the css block to undo the effect
some-type: inherit;
I would go with jQuery or some other Javascript Framework, the selectors just rock and NOT class XY is rather easy to achieve.
As Pekka pointed out I am not sure what brothers you want to target. getElementsByClassName() is implemented by almost all browsers (you know which one doesn't work, don't you?).
I found a rather nifty solution on devshed to also make it work in IE:
onload=function(){
if (document.getElementsByClassName == undefined) {
document.getElementsByClassName = function(className)
{
var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
var allElements = document.getElementsByTagName("*");
var results = [];
var element;
for (var i = 0; (element = allElements[i]) != null; i++) {
var elementClass = element.className;
if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
results.push(element);
}
return results;
}
}
}
All you need to do now is to iterate through all your div classes and negate the one you DON'T want.

Having problems with grabbing image dimensions with jQuery

I'm having a hard time picking up how to grab the dimensions of an element with jQuery. Here is my sample code:
$(document).ready(function() {
var width = $("#image_1").width();
var height = $("#image_1").height();
document.write(width);
document.write(height);
});
Now of course I have an image with an id of #image_1. What happens when I try to run it is that it outputs two zeros. Not null twice, or undefined twice.
Thanks for the help from a javascript newb.
Even though you've already chosen an answer, I am typing this one so you understand why your prior code did not work.
jQuery's document.ready function fires before images are loaded. Use window.load instead...
$(window).load(function() {
var width = $("#image_1").width();
var height = $("#image_1").height();
document.write(width);
document.write(height);
});
For what it's worth, I think it is better to use jQuery for this task because of the inherent cross-browser functionality.
Perhaps this was a typo in your question, but is the ID of your image really "#image_1"? For your code to work, it should be just "image_1". The "#" is only used in the jquery selector to specify that the text following it is an ID.
You may get 0 for the width and height if the image is not visible. (That's what just happened to me.)
Updated: You can confirm that the image is added to the DOM by checking the length property of the jQuery object:
var inDOM = ($('#image_1').length > 0);
This works for me:
<head>
<script type="text/javascript">
function foo() {
var image = document.getElementById("the_image");
alert(image.offsetWidth);
alert(image.offsetHeight);
}
</script>
</head>
<body onload="foo();">
<img src="img.png" id="the_image">
</body>
This works as long as the image is not set to display: none; Using offsetWidth and offsetHeight also has the advantage of not requiring jQuery, at all.

Resources