Change an image using only CSS. - javascript

I have something like
<a href="OnlyThisONE"
<img class="SameClassForAllIMG" src="random.png">
</a>
I would like to replace the image which something else using only CSS. Is this possible?
Here is the Javascript solution.
var images = document.getElementsByTagName('IMG');
for (var i = 0; i < images.length; ++i) {
if (images[i].src == "random.png")
images[i].src = 'new.png';
}
Here is a possible CSS solution
.SameClassForAllIMG {
background: url(new.png) no-repeat;
}
The issue is the CSS should do it for the IMG only under the "OnlyThisONE" href, and not all of them. Is this possible using only CSS?

This is possible using only CSS. You can target the image using a[href='OnlyThisONE'] and hide the <img> tag within, then apply a background to the <a> link.
CSS
a[href='OnlyThisONE'] img {
display: none;
}
a[href='OnlyThisONE'] {
background: url('somebackground.jpg');
width: 100px;
height: 100px;
display: block;
}

In CSS you could use either pseudo-element on <a> or a background-image in <a> or even in <img> that can only be seen on hover.
here is 2 demo
one using a pseudo-element
one using the img tag with a background. (no src changed).
http://codepen.io/anon/pen/Jchjw
<p>Set background-image, and resize it to zero with padding on :hover
<a href="#nature"><img class="a-img" src="http://lorempixel.com/120/80/nature/1">
</a></p>
<p>use a pseudo-element set in absolute position and overflow in a tag :
<a href="#nature3"><img class="a-img" src="http://lorempixel.com/120/80/nature/3">
</a></p>
img {
vertical-align:middle;
}
[href="#nature"]:hover .a-img {
height:0;
width:0;
padding:40px 60px;
background:url(http://lorempixel.com/120/80/nature/2);
}
[href="#nature3"] {
display:inline-block;
vertical-align:middle;
position:relative;
overflow:hidden;
}
[href="#nature3"]:after {
content:url(http://lorempixel.com/120/80/nature/4);
vertical-align:top;
position:absolute;
}
[href="#nature3"]:hover:after {
left:0;
}
The a:hover + img background works with oldest IE an it keeps the alt attribute useful, this would be my choice. pseudo-element :after/:before works from IE8, but not the ::*after/::*before syntaxe.
theres in css of course, many other solution working with a or img with or without a translucide gif/png :( ....

There are a few approaches you could use. In my opinion, the best one is #1, as it has the broadest browser support and it avoids the use of JS.
1 - You could select just that a (assuming the href is unique), show a background image, and then hide the contained image. You'll also need to specify width, height, anddisplayon thea`:
a[href$='OnlyThisONE'] img {
display: none; /* hide the image that's there */
}
a[href$='OnlyThisONE'] {
background: url(someOtherImage.jpg) /* show another image as a background */
display: inline-block;
height: 100px;
width: 100px;
}
2 - Use content:url(), but it doesn't have broad browser support
- Is it possible to set the equivalent of a src attribute of an img tag in CSS? After running a quick self-check on support of content:url() I would not suggest doing this, at all. I could only get it to work in Chrome. Try it yourself: http://jsfiddle.net/3BRN7/49/
a[href$='OnlyThisONE'] img {
content:url("newImage.jpg");
}
3 - Use JavaScript as you have in your question.

If the src is "random.png", "new.png" will be displayed.
HTML
<a href="#">
<img class="SameClassForAllIMG" src="//dummyimage.com/300x100/111/fff&text=random.png">
<span></span>
</a>
<a href="#">
<img class="SameClassForAllIMG" src="//dummyimage.com/300x100/111/fff&text=images.png">
<span></span>
</a>
CSS
img.SameClassForAllIMG[src*="random.png"] {
display: none;
}
img.SameClassForAllIMG[src*="random.png"] + span {
display: inline-block;
width: 300px;
height: 100px;
background: url(//dummyimage.com/300x100/111/fff&text=new.png) no-repeat left top;
}
I guess that this code is the same as your JavaScript solution.
IE7>= version http://jsfiddle.net/nxvm7/1/
IE8>= version http://jsfiddle.net/nxvm7/2/

Related

need help removing an IMG and replacing it with text in its position with javascript

Im working on a project and a part of it is making an image disapear on hover, and replace that with text in the same location! I have to do it through javascript.
im very new to front end web development so any help would be great!
.main-img1{
height: 400px;
width: 600px;
margin-top: 80px;
background-size: 600px 400px;
box-shadow: 10px 10px 5px rgb(24, 22, 22);
position: relative;
text-align: center;
font-size: 25px;
color: black;
border-radius: 50px;
}
.img1-text{
display: none;
position: absolute;
bottom: 8px;
left: 150px;
<section class="main-body">
<div>
<img class="main-img1" src="img/automotive.jpg">
<h1 class="img1-text" id="img1text"> Here are some samples of my automotive photography! I specialize in "Rolling Shots" which are caputring a vehicle in motion, while the background and foreground show the motion.</h1>
</div>
You can replace any element using the "magical" outerHTML like this...
First, I gave your image an ID to make javascript operations easier...
<img id="I" class="main-img1" src="img/automotive.jpg">
Now replace the image with a paragraph of text...
I.outerHTML='<p>Well what do you know!</p>';
For easy one-line HTML...
<img onmouseover="this.outerHTML='<p>Well what do you know!</p>';" class="main-img1" src="img/automotive.jpg">
First off, this is a very odd thing to do in Javascript. Usually hover states, appearing and disappearing, etc. are handled by CSS.
to do it in js you have to add a mouseover event listener to the image to execute a function to grab the element you want to disappear, add a css class to apply "display: none" to it, grab the element you want to appear and remove a class that adds "display: none" from it.
assuming you have a 'display-none' class on your text element that applies 'display: none' to it, you can do this:
const image = document.querySelector('.main-image1')
const text = document.querySelector('.img1-text')
image.addEventListener('mouseover', () => {
image.classList.add('display-none')
text.classList.remove('display-none')
}
if you were to do this with css its as simple as
.image {
z-index: 2;
}
.image:hover {
display: none;
}
.text {
z-index: 1;
}
that way the text is set behind the image and when you hover over the image it disappears. This also has the benefit of when you take your cursor off the image for the image to reappear where js will need to be told explicitly to do that.

Hover disabled after style change: important doesn't work

My problem is as follows: I have a clickable div with a background-image that changes (the image) on :hover.
This div kind of represents a menu button. When the div is pressed a script is executed that changes the background-image too.
However, I want the hover to still work after running this script. I have read about the style priorities and that I should use !important with the hover. I have used this before without problems, but for some reason the hover doesn't work, even with !important. Does this have something to do with background-image, can't this be combined with !important?
The div:
<a href="#" onclick="open_Thema(1);">
<div id="venster_Links_Menu_1">
<div class="venster_Links_Menu_Tekst">Introductie</div>
</div>
</a>
The css:
#venster_Links_Menu_1 {
margin: 0;
height: calc((100%/6) - 1px);
border-bottom: 1px solid white;
width: 100%;
background-image: url(images/Thema_1_Half.png);
background-size: cover;
position:relative;
}
#venster_Links_Menu_1:hover {
background-image: url(images/Thema_1.png); !important
}
And the script:
<script>
var themaOud = 0;
function init(){
}
function open_Thema(themaNieuw){
if (themaOud != 0)
{
document.getElementById("venster_Links_Menu_"+themaOud).style.backgroundImage="url(images/Thema_"+themaOud+"_Half.png)";
}
document.getElementById("venster_Links_Menu_"+themaNieuw).style.backgroundImage="url(images/Thema_"+themaNieuw+".png)";
themaOud = themaNieuw;
}
</script>
The correct way to write an important would be
!important;
not
; !important
Notice the placement of the semicolon.

Modifying the background on a :before style in Javascript. (No libraries)

In my application I am making use of the :before for an image background. This is to "sharpen" the image that's in the container, as it's using a -webkit-filter: blur().
The issue is that I cannot find a way to change the :before style using Javascript. I need to change the background image to be whatever the foreground image is.
Example CSS:
#image-container:before {
background: url(img.png);
content: '';
position: fixed;
z-index: -1;
display: block;
height: 40%;
}
#image-container {
position: relative;
width: 100%;
height: 58%;
overflow: hidden;
}
.blur {
-webkit-filter: blur(10px);
}
Inside the image container I have the following code:
<div id="image-container">
<img class="blur" src="img.png" width="100%" height="100%">
</div>
The issue is that the img source is actually coming in from my server, so I need the background to match up with the image so the edges (from the blur) don't look sloppy and conflicted.
So the question here is, how can I change the background: url() value on the #image-container:before CSS style?
No libraries. Pure Javascript.
Try below code. For the reference -
http://davidwalsh.name/pseudo-element
http://pankajparashar.com/posts/modify-pseudo-elements-css/
Your css is like this
#image-container:before {
background: url(img.png);
content: '';
position: fixed;
z-index: -1;
display: block;
height: 40%;
}
Below is js to get background
var color = window.getComputedStyle(
document.querySelector('#image-container'), ':before'
).getPropertyValue('color')
And to set the new css property
var style = document.createElement("style");
// Append the style tag to head
document.head.appendChild(style);
// Grab the stylesheet object
sheet = style.sheet
// Use addRule or insertRule to inject styles
sheet.addRule('#image-container::before','color: green');
sheet.insertRule('#image-container::before { color: green }', 0);

overlaying an image with a button on html page

so I have an image which i would like to overlay with an html button attribute like so:
here is a blank image
i would like to overlay a button like so on the image
and then if the button is clicked have it then look like this
from what i can gather this could be done using CSS using {index-z} somehow, or possible with html5 canvas tag. and then to handle the actually button click with java script.
However i am not completely sure how to accomplish this (the handling of button click with javascript i do know). Could someone link to a tutorial on how to do this or give an explanation it would be greatly appreciated.
Note: the image itself is also an href / link if this changes how this should be done, additionally te image itself will be in a sort of gallery with around 50 similar images or so
You can use positioning to place the "star" button on top of the other image. Your image and button will need to be in a container with the position set to relative. Then you can set your "star" to be absolutely positioned, and that position will be relative to the container:
.image-container {
display: inline-block;
position: relative;
}
.star-button {
position: absolute;
right: 10px;
top: 10px;
}
<div class="image-container">
<img src="main image here">
<img class="star-button" src="star image here">
</div>
Then you can handle the click of the image (or button, or a, or what have you) in your javascript.
JSFiddle
Maybe this example will help you my friend:
Source: ye5
HTML :
<div id="header1" width="259px">
<img src='http://2aek.com/inventory/MyBlogspot/ye5-templete/ye5Header3b.jpg' style='margin-left:259px; margin-top:-128px;'/>
CSS :
#header1 a {
background-image: url(http://2aek.com/inventory/MyBlogspot/ye5-templete/ye5Header3a1.jpg);
height:128px;
width:259px;
display: block;
}
#header1 a:link {
background-image: url(http://2aek.com/inventory/MyBlogspot/ye5-templete/ye5Header3a1.jpg);
height:128px;
width:259px;
display: block;
}
#header1 a:hover {
background-image: url(http://2aek.com/inventory/MyBlogspot/ye5-templete/ye5Header3a2.jpg);
height:128px;
width:259px;
display: block;
}
#header1 a:active {
background-image: url(http://2aek.com/inventory/MyBlogspot/ye5 templete/ye5Header3a3.jpg);
height:128px;
width:259px;
display: block;
}

Position badge over corner of image automatically

I have a layout where images "float" within a certain area. The layout looks like this:
The source like this:
<div class="free_tile">
<a class="img_container canonical" href="/photos/10">
<img class="canonical" src="http://s3.amazonaws.com/t4e-development/photos/1/10/andrew_burleson_10_tile.jpg?1303238025" alt="Andrew_burleson_10_tile">
<!-- EDIT: I am aware that I can put the badge here. See the edit notes and image below. -->
</a>
<div class="location">Houston</div>
<div class="taxonomy"> T6 | Conduit | Infrastructure </div>
</div>
The CSS looks like this (in SCSS):
div.free_tile { width: 176px; height: 206px; float: left; margin: 0 20px 20px 0; position: relative;
&.last { margin: 0 0 20px 0; }
a.img_container { display: block; width: 176px; height: 158px; text-align: center; line-height: 156px; margin-bottom: 10px; }
img { margin: 0; border: 1px solid $dark3; display: inline-block; vertical-align: middle; #include boxShadow;
&.canonical { border: 1px solid $transect; }
}
.location, .taxonomy { width: 176px; }
.location { font-weight: 700; }
.taxonomy { line-height: 10px; font-size: 10px; text-transform: uppercase; height: 20px; overflow: hidden; }
}
div.transect_badge { height: 20px; width: 20px; background: url('/images/transect-badge.png'); }
So, basically the images are sitting vertically-aligned middle and text-aligned center, and they have a maximum width of 176 and max height of 158, but they're cropped to maintain the original aspect ratio so the actual top corner of each image falls differently depending on which image it is.
I have a badge that I'd like to put in the top corner of certain images (when the image is "canonical"). You see the style for this above (div.transect_badge).
The problem, of course, is I don't know where the top corner of the image will be so I can't hardcode the position via CSS.
I assume that I'll need to do this via jQuery or something. So, I started with a jQuery method to automatically append the badge div to any canonical images. That works fine, but I can't figure out how to position it over the top left corner.
How can this be done? (ideally using just HTML and CSS, but realistically using JS/jQuery)
--EDIT--
Here's the problem: The image is floating inside a container, so the corner of the image might fall anywhere inside the outer limits of the container. Here's an example of what happens if I try to use position:absolute; top:0; left:0 inside the same container the image is bound by:
It took some tryouts, but here it is: the size independent image badge positioner.
HTML:
<div class="tile">
<span class="photo">
<img src="/photos/10.jpg" alt="10" /><ins></ins>
</span>
<p class="location">Houston</p>
<p class="taxonomy">T6 | Conduit | Infrastructure</p>
</div>
CSS:
.tile {
float: left;
width: 176px;
height: 206px;
margin: 0 20px 20px 0;
}
.photo {
display: block;
width: 176px;
height: 158px;
text-align: center;
line-height: 158px;
margin-bottom: 10px;
}
a {
display: inline-block;
position: relative;
line-height: 0;
}
img {
border: none;
vertical-align: middle;
}
ins {
background: url('/images/badge.png') no-repeat 0 0;
position: absolute;
left: 0;
top: 0;
width: 20px;
height: 20px;
}
Example:
In previous less successful attempts (see edit history), the problem was getting the image vertically centered ánd to get its parent the same size (in order to position the badge in the top-left of that parent). As inline element that parent doesn't care about the height of its contents and thus remains to small, but as block element it stretches to hís parent's size and thus got to high, see demonstration fiddle. The trick seems to be to give that parent a very small line-height (e.g. 0) and display it as an inline-block. That way the parent will grow according to its childs.
Tested in Opera 11, Chrome 11, IE8, IE9, FF4 and Safari 5 with all DTD's. IE7 fails, but a center-top alignment of the photo with badge at the right position isn't that bad at all. Works also for IE7 now because I deleted the spaces in the markup within the a tag. Haha, how weird!
EDIT3: This solution is very similar to my original solution. I didn't really look at your code much so I should have noticed this earlier. Your a tag is already wrapping each image so you can just add the badge in there and position it absolute. The a tag doesn't need width/height. Also you must add the badge image at the beginning of your a tag.
Demo: http://jsfiddle.net/wdm954/czxj2/1/
div.free_tile {
width: 176px;
height: 206px;
float: left;
}
a.img_container {
display: block;
margin-bottom: 10px;
}
span.transect_badge {
display:block;
position: absolute;
height: 20px;
width: 20px;
background-image: url('/images/transect-badge.png');
}
HTML...
<a class="img_container canonical" href="/photos/10">
<span class="transect_badge"></span>
<img class="canonical" src="path/to/img" />
</a>
Other solutions...
In my code I'm using SPAN tags so simulate images, but it's the same idea. The badge image, when positioned absolute, will create the desired effect.
Demo: http://jsfiddle.net/wdm954/62faE/
EDIT: In the case that you need jQuery to position. This should work (where .box is your container and .corner is the badge image)...
$('.box').each(function() {
$(this).find('.corner')
.css('margin-top', ( $(this).width() - $(this).find('.img').width() ) / 2);
$(this).find('.corner')
.css('margin-left', ( $(this).height() - $(this).find('.img').height() ) / 2);
});
EDIT2: Another solution would be to wrap each image with a new container. You would have to move the code that you use to center each image to the class of the new wrapping container.
Demo: http://jsfiddle.net/wdm954/62faE/1/
$('.img').wrap('<span class="imgwrap" />');
$('.imgwrap').prepend('<span class="badge" />');
Technically you can just add something like this to your HTML though without using jQuery to insert it.
Use an element other than <div>, e.g. <span> and put it inside your <a> element after the <img> element. Then, give the <a> element position:relative; and the <span> gets position:absolute; top:0px; left:0px;. That is, if you don't mind the badge also being part of the same link - but it's the easiest way. Also, the reason for using <span> is to keep your HTML4 valid, <div> would still be HTML5 valid, however.
I did find one solution using jQuery. I don't prefer this because it noticably impacts page loading, but it is acceptable if nothing else will work. I'm more interested in NGLN's idea which seems promising but I haven't entirely figured out yet. However, since this thread has picked up a lot of traffic I thought I'd post one solution that I came up with for future readers to consider:
Given this markup:
<div class="free_tile">
<a class="img_container canonical" href="/photos/10">
<img class="canonical" src="http://s3.amazonaws.com/t4e-development/photos/1/10/andrew_burleson_10_tile.jpg?1303238025" alt="Andrew_burleson_10_tile">
<span class="transect-badge"></span>
</a>
<div class="location">Houston</div>
<div class="taxonomy"> T6 | Conduit | Infrastructure </div>
</div>
Same CSS as in question except:
span.transect-badge { display: block; height: 20px; width: 20px; position: absolute; background: url('/images/transect-badge.png'); }
Then this jQuery solves the problem:
$(function() {
$('img.canonical').load( function() {
var position = $(this).position();
$(this).next().css({ 'top': position.top+1, 'left': position.left+1 });
});
});
Like I said, though, this incurs noticeable run-time on the client end, so I'd prefer to use a non JS solution if I can. I'll continue to leave this question open while I test out and give feedback on the other solutions offered, with hopes of finding one of them workable without JS.

Categories

Resources