Adding CSS classes and media to an empty div and append - javascript

I'm trying to re-create an Instagram like sort of page with some jQuery included. This is for a course I'm taking, so I'm a student basically.
This particular part of the exercise is asking me to:
- Empty the content of a class div.
- iterate over the media that is given.
- create an empty div and assign two classes, background image and append to the "empty" class.
The code I have so far is the following:
function renderUserMedia (media) {
// The class that is being emptied.
$('.user-media').html('');
// iteration
media.forEach(function (mediaItem) {
// empty div to add to every iterated picture with whatever is needed
var div = $('<div>').addClass('user-media-item u-pull-left').css('background-image', mediaItem).appendTo('.user-media');
});
}
All media is fetched through an API which I have no idea how is being configured (school configuration and what not), and the media is from a "dummy" insta page I guess.
What's happening is that images are not happening on the browser, and I think it has something to do with the .css implementation of the images iterated. The property background-image does not exist in the css file, so there might be something going on.
I have also tried to append to '.user-media' with $('.user-media').append(div); on the next line, but it didn't produce the desired result, which is to have all pictures iterated from forEach with the '.user-media-item' class.
.user-media-item {
margin-right: 10px;
margin-bottom: 10px;
width: 230px;
height: 230px;
overflow: hidden;
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}
Could someone please help me understand what am I doing wrong?

After having checked everything and not being able to retrieve images, the only needed thing was (thanks to #freedomn-m and #CBroe for directions) to include the actual key that holds the location of the file. In this case a local folder.
function renderUserMedia (media) {
$('.user-media').html('');
media.forEach(function (mediaItem) {
var div = $('<div>').addClass('user-media-item u-pull-left').css('background-image', 'url(' + mediaItem.media_url + ')').appendTo('.user-media');
});
}
In case of using the url key, then we should change to .css('background-image', 'url(' + mediaItem.permalink + ')') as it was showing in the object containing the info of the images.

Related

Issue with changing the background image using the .css() jQuery method

I am using the .css() jQuery method to change the background of a div with an ID of "background". The method accepts as parameters the property name and the value you want to set for it. Therefore, my code is as follows:
function changeBackground() {
$("#background").css("background-image", "url(../assets/background2.jpg)");
}
window.onload = function() {
window.addEventListener("click", changeBackground);
};
Originally, background-image had a value of url(../assets/background.jpg). The curious thing is that it works fine in the Chrome session that my editor (Brackets.io) uses as Live Preview, but it doesn't when I open Chrome normally or I use Firefox and Opera.
EDIT: The issue was with the path: instead of temporarily changing the value in the css sheet (what I thought the code did), apparently jQuery itself makes sure the background source changes. This means that the path for the image must be set relative to the javascript file—in this case url(assets/background2.jpg) instead of url(../assets/background2.jpg). I'd like anyone more knowledgeable or better spoken to correct me if needed.
However, another issue arose—the rest of the styling for the background image (see below) gets completely ignored after jQuery changed its source. How can you fix this?
#background {
background-image: url(../assets/background.jpg);
background-attachment: fixed;
background-position: center;
background-size: cover;
position: fixed;
top: 0em;
left: 0em;
height: 100%;
width: 100%;
margin: 0em;
}
Use ' instead of " :
$("#background").css("background-image", 'url(../assets/background2.jpg)');
If doesn't work, try this
$("#background").css({backgroundImage : 'url(../assets/background2.jpg)'});
or this
$("#background").css('background', 'url("../assets/background2.jpg")');
add class .new-background
// css
.new-background {
background-image: url(../assets/background2.jpg);
}
and
// js
function changeBackground() {
$("#background").addClass('new-background');
}
$(window).click(changeBackground);

Standardize image into div

I'm working with Bootstrap and I want to put some photos into my div and I want them to be all at the same size ("standardize").
If they're too big (and they will always be) I want to resize them to fit in my div and crop them if necessary.
For the moment her is what I do :
I've tried to change the style of the image in jQuery in a function:
• If the height is bigger than the width, I switch the style to max-width:100% and height auto.
• Inversement if the width is bigger than the height.
But I'm still new to jQuery and I am probably doing something wrong; can someone light my lantern please?
Here is my jQuery
$(document).ready(function(){
photoResize();
$(window).resize(function(){
photoResize();
});
});
function photoResize(){
image_w = $('img').width();
image_h = $('img').height();
if(image_h > image_w)
{
$('img').css("max-width","100%");
$('img').height("auto");
}
else if(image_w > image_h)
{
$('img').css("max-height","100%");
$('img').width("auto");
}
}
And here is a Fiddle for a better view : https://jsfiddle.net/Baldrani/DTcHh/9801/
Simplicity
I do this quite often in the CMS we use at work for galleries etc. The method I use involves a jQuery library called imgLiquid.js.
This will turn an inline image into a background image on the parent div. It's good because you can achieve your desired effect. It will crop the image (as it technically becomes a background image) and will apply background-size: cover; and background-position: center center; as inline styles.
You can find the plugin here
To initialize the plugin you just need:
$(".myele").imgLiquid();
Overheads
The plugin is very small (roughly around 5.106 KB) so you don't need to worry about adding weight to the page. It really it the most simple method I've come across (bar using thumbnails generated from the sever-side - see note at the bottom).
Cue CSS
I've tested this thoroughly and found it gives excellent results. You may then ask... what happens to my parent divs (as technically the plugin hides the img element - which therefore means the parent element doesn't know what height to make itself).
An easy method to make things work responsively, or not:
.myelement:before{
content: "";
padding-top: 50%;
display: block;
}
This CSS will give your heights back to the wrapping element. So if you wanted certain proportions you could use this math:
h / w * 100 = your percentage for the padding-top.
Working Example
Small note
Technically if I had the control I'd advise just using thumbnails.. I assume you're using some sort of system that could technically just render cut down versions of the images? The reason I use this method — and suggested it — is that I don't have control over the CMS and I'm assuming you just want to manage the code that's being produced as it's not stated.
if you want to make your images the same size then you dont need any javascript or calculations, why not just set it in css?
.someUniqueContainer img{
width:300px;
height:300px; // or what ever height you want
}
I'm guessing that in reality you actually want to crop all your images to a set width/height. if that's the case you'll need a serverside script for that.
where are the images coming from? it would be easyer to just edit them. if they are coming from a user then you would resize/crop on the server on file upload
There were several mistakes in your code.
Please look at this jsfiddle, please see https://jsfiddle.net/DTcHh/9796/
$(document).ready(function () {
photoResize();
$(window).resize(function () {
photoResize();
});
});
function photoResize() {
image_w = $('img').width();
image_h = $('img').height();
if (image_h > image_w) {
$('img').css("max-width", "100%");
$('img').height("auto");
} else if (image_w > image_h) {
$('img').css("max-height", "100%");
$('img').width("auto");
}
}
sth like this?, although this is pure css, not jquery included, might not be suit in your case..
body {
margin-top:20px
}
.col-xs-3 {
margin: 5px 0;
width: 500px;
height:120px
}
.col-xs-3 > div {
width: 100%;
height: 120px;
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
JsFiddle

Declaring a single image from a sprite sheet in javascript

I'm trying to define and declare an image from a sprite sheet in javascript.
I've defined the image within an external style sheet as follows:
#myimage{ background-position: 0 -751px; width: 21px; height: 21px; }
.dwg { background:url(spriteSheet.png) no-repeat;}
I've tried various arrangements similar to the following, none of which, of course, works.
myimage=new Image();
myimage.src="background:url('spriteSheet.png') 0 0; width: 35px; height: 16px; no-repeat";
I use the image as follows:
document.stat.src = myimage.src;
My Javascript conditional logic switches between various images depending upon status. The code has worked fine with individual images, but I have combined them into a sprite sheet and now need to assign individual images from the sheet. And in order to do so, I need to define each image as a JavaScript variable.
What should be inserted in place of the background: url... string?
A few months I a started using the following approach and it became the easiest to me:
JS code:
$('[class*=sprite-]').each(function(){
var crr = this.className.match(/sprite\-(\d+)\-(\d+)/);
if ( crr && crr[2]) {
$(this).css('background-position', '-'+ crr[1] +'px -'+ crr[2] +'px');
$(this).addClass('sprite');
}
});
CSS code:
.sprite {
border: none;
background-color: transparent;
background-image: url(your-sprite-image.gif);
background-repeat: no-repeat;
}
HTML code (You may replace "50x50" by your sprite coordinate):
<img class="sprite-50-50" width="100" height="200" src="use-a-blank-image.gif" alt="" >
I am not 100% sure what you are trying to do because the code is a little weird. The src attribute is the src of the image. If you are doing a sprite... then you should probably be using a div tag, not even using an img. Sprites are usually not "img" tags, but usually "div" tags that are formatted to show just a single frame of your sprite sheet using a background-image. You would only need to adjust the background properties of the div using backgroundImage and backgroundPosition properties and show the sprite you have created. There is no reason to create an Image object in javascript and try to apply it to your code.

How to override HTML image using CSS

I have my current code:
#content img[src="/img/test.gif"] {
background-image:url(dark-img.png) !important;
}
From my understanding !important; overrides existing values?
Why isn't this overriding the current HTML image in place there? The background shows up, behind the HTML image.
I want it in front of the HTML image, is this possible using CSS or JS?
Edit: For what its worth, im making a userscript that will modify the existing style of the site. So I do not have direct access to the HTML image.
You don't need javascript for image replacement! As long as you can identify the image by a CSS selector, you can use CSS to do the trick.
See the solution here
http://www.audenaerde.org/csstricks.html#imagereplacecss
Here is the code using only css:
<img src="tiger.jpg"
style="padding: 150px 200px 0px 0px;
background: url('butterfly.jpg');
background-size:auto;
width:0px;
height: 0px;">
sets the image size to 0x0,
adds a border of the desired size (150x200), and
uses your image as a background-image to fill.
If you upvote this answer, give #RobAu's answer an upvote, too.
The replacement of an image in CSS can be done in several ways.
Each of them has some drawbacks (like semantics, seo, browsercompatibility,...)
On this link 9 (nine!) different techniques are discussed in a very good way :
http://css-tricks.com/css-image-replacement/
If you are interested in css in general : the whole site is worth a look.
The background-image property, when applied to an image, refers to (drum roll ... ) the background-image of the image. It will always be behind the image.
If you want the image to appear in front of the image, you are going to have to use two images, or another container with a background-image that covers the first image.
BTW, it is bad practice to rely on !important for overriding. It can also be ineffective since 1) it can't override declarations in an element's style attribute, and 2) it only works if it can work based on the markup and the current CSS. In your case, all the huffing and puffing and !important declarations won't make an image do something it can't do.
I answered a similar question in another SO page..
https://robau.wordpress.com/2012/04/20/override-image-src-in-css/
<img src="linkToImage.jpg" class="egg">
.egg {
width: 100%;
height: 0;
padding: 0 0 200px 0;
background-image: url(linkToImage.jpg);
background-size: cover;
}
So effectively hiding the image and padding down the background. Oh what a hack but if you want an with alt text and a background that can scale without using Javascript?
Use your 'userscript' to change 'src' attribute value.
If there is an ID there, you can do this:
document.getElementById('TheImgId').src = 'yournewimagesrc';
If there is no ID:
var imgElements = document.getElementsByTagName('img');
Do iteration of imgElements. When its src value is match with your criteria, change the value with your own, do break.
Update:
Javascript:
<script language="javascript">
function ChangeImageSrc(oldSrc, newSrc) {
var imgElements = document.getElementsByTagName('img');
for (i = 0; i < imgElements.length; i++){
if (imgElements[i].src == oldSrc){
imgElements[i].src = newSrc;
break;
}
}
}
</script>
HTML:
<img src="http://i.stack.imgur.com/eu757.png" />
<img src="http://i.stack.imgur.com/IPB9t.png" />
<img src="http://i.stack.imgur.com/IPB9t.png" />
<script language="javascript">
setTimeout("ChangeImageSrc('http://i.stack.imgur.com/eu757.png', 'http://i.stack.imgur.com/IPB9t.png')", 5000);
</script>
Preview:
The first image will be replaced after 5 secs. Try Live Demo.
you'll have to place the first image as a background-image too. Then you can override it. You could do in a "standard" css file for the site, and every user gets its own, where he can override what he wants.
i agree with all the answers here, just thought id point out that 'browsers' such as IE won't like the img[src="/img/test.gif"] as a means of selecting the image. it would need a class or id.
The images shown in tags are in the foreground of the element, not the background, so setting a background image in an won't override the image; it'll just appear behind the main image, as you're seeing.
What you want to do is replace the image. Here's your options:
Start with an element with a background image, not an tag. Then changing the background image in CSS will replace it.
Start with an tag, but use Javascript to change the src attribute. (this can't be done in CSS, but is simple enough in JS)
EDIT:
Seeing your edit in the question, I'd suggest option 2 - use Javascript to change the src attribute. It's quite simple; something like this would do the trick:
document.getElementById('myimgelement').src='/newgraphic.jpg';
You should be able to replace it by just doing something like:
.image {
content: url('https://picsum.photos/seed/picsum/400');
width: 200px;
height: 200px;
}
Unfortunately seems that it does not work in Firefox :(

Making a DOS-style window in ASP.net

I'm trying emulate the MS-DOS command prompt on my website. I don't need to accept keystrokes, but I'd like to append data at the bottom and optionally scroll upwards.
At first I looked at the asp:TextBox and asp:Label, but the flicker of using postbacks seemed to be too much. I'm now considering DIV tags and Javascript where I simply update the InnerHTML property, but there too I get flicker, and have issues with scrolling.
What solution would you recommend in this situation? Essentially I'm trying to count to infinity, with a 1 sec delay, only need the most current 300 or so entries, with the most current entry at the bottom of the screen.
Is this even possible with JS/CSS?
Do you wish to make it a little more stylous ? :)
see this page...
http://www.klaus.dk/Some_unknown_page
or this one
http://www.harryovers.com/404.html?aspxerrorpath=/Account/LoginPartial
here is the javascript source code.
http://code.google.com/p/c64-404-page/
With a little change, you can append your text on this code :)
I just built something very similar using jQuery. You can use the append method to add content to the bottom of your DIV. You can then set the scrollTop attribute to keep things scrolled to the bottom as follows:
$("#someDiv").attr({ scrollTop: $("#someDiv").attr("scrollHeight") });
I think "DOS-style window" is a bit misleading considering all you want to do is append text to a div and make sure it stays scrolled to the bottom.
function addLine(text) {
var box = document.getElementById('DOSBox') //teehee
var line = document.createElement('p');
line.innerHTML = text;
box.appendChild(line);
box.scrollTop = box.scrollHeight;
}
And style it as such
#DOSBox {
overflow: auto;
display: block;
height: 400px; width: 500px; /* or whatever */
/* and if you want it to look DOS-like */
background: #000;
color: rgb(192, 192, 192);
font-family: fixedsys;
}
#DOSBox p {
margin: 0;
}

Categories