Javascript: get an image width and than set a class - javascript

I want to analyse every image of an article and set an class for all images smaller/equal than perhaps 400px (and another class for images bigger than 400px) so that I can give them a specific style.
In jQuery it would be perhaps something like this
$('div#content').find('img').each(function () {
var $this = $(this), width = $this.width();
if (width <= 400) {
$this.addClass('small_img');
}
var $this = $(this), width = $this.width();
if (width > 400) {
$this.addClass('large_img');
}
});
But I need it to be in pure Javascript. As a stupid Journalist and Webdesigner I don't get it... If you could help me, I would be very thankful.

You mean something FAST and short like this?
window.onload = function() {
var n=document.getElementById('content').getElementsByTagName('img'),
i=n.length;
while(i--){
n[i].className = n[i].clientWidth > 400 ? 'large_img' : 'small_img' ;
}
};
See this fiddle for working example.
Also read this question on SO for selecting a method to fetch the (computed) width.

window.onload = function() {
var content = document.getElementById('content');
if (content) {
var img = content.getElementsByTagName('img');
for (var i = 0, count = img.length; i < count; i++) {
if (img[i].offsetWidth <= 400) {
img[i].className += ' small_img';
} else {
img[i].className += ' large_img';
}
}
}
};

Something like this should work:
// Find the parent container 'div#content'
var container = document.getElementById( "content" ),
// Find all images within the parent
images = container.getElementsByTagName( "img" ),
// Total number of images to check
len = images.length,
// Loop counter
i = 0,
// Represents the current image in the loop
image;
// Loop through all the images
for ( ; i < len; i++ ) {
// Access the current image
image = images[ i ];
// Use the ternary operator to assign one of two classes, based on width
image.className += ( image.clientWidth > 400 ) ? " large_img" : " small_img";
}
Hope that helps. Cheers!

var contentDiv = document.getElementById('content');
var imgs = contentDiv.getElementsByTagName('img');
for(i=0;i<img.length;i++){
var img = imgs[i];
if(img.clientWidth <= 400) img.className += " small_img"
else img.className += " large_img"
}

Related

How to make all div height inside a row div similar height to the first child of row

I want to change all div inside row be similar to the height of firstchild of row2 also if the classes are outside of row the div height will be auto and not be change. what's the problem in my code can anyone explain also I dont want to change it from css.
var lgh , lgh_in,mdh,mdh_in,smh,smh_in;
var r = ".row2 >";
var z = ['.lg','.lg-in','.md','.md-in','.sm','.sm-in',];
z.forEach(function (x){
var xx = document.querySelectorAll( r + x );
for ( var j = 0; j < xx.length; j++) {
var ch = document.getElementsByClassName('row2');
for(var i = 0 ; i < ch.length ; i++ ){
var ar = ['lg','lg-in','mdh','md-in','sm','sm-in']; //these are class names , if I put this into my div the div height should be change according to mdh ,lgh ,smh .... etc
for(var k = 0; k < ar.length;k++){
if(ch[i].firstChild.className === ar[k]){
lgh = ch[i].parentNode.clientHeight/ 1.5 ;
lgh_in = ch[i].parentNode.clientHeight - lgh ;
mdh = lgh/ 1.5 ;
mdh_in = ch[i].parentNode.clientHeight - mdh ;
smh = mdh/ 1.5 ;
smh_in = ch[i].parentNode.clientHeight - smh ;
var colors = {};
colors[ar[0]] = lgh;
colors[ar[1]] = lgh_in;
colors[ar[2]] = mdh;
colors[ar[3]] = mdh_in;
colors[ar[4]] = smh;
colors[ar[5]] = smh_in;
ch[i].firstChild.style.height = mdh + "px"; //if I remove the px then output is different also
document.getElementById('demo').innerHTML = mdh ; // only for output checking
if (ch[i].parentNode.tagName === "BODY") {
ch[i].style.height = "auto"; // if the div2 parent is body then height will be auto.
}
}
}
}
}
});
so I able to change the first child div but I cant change all div inside of the row2 which is my problem,
HTML
<div class="main"><div class="row2"><div class="lg">xfghjgjgx</div><div class="lg-in">xfgvcbvx</div></div>
<div class="row2"><div class="lg-in">xfghjgjgx</div><div class="lg">xfgvcbvx</div></div>
Jquery is easier.. Id do something like this?
// For each .box element
$('.box').each(function() {
// Set up the variables
var $this = $(this),
w = $this.find('img').width(), // Width of the image inside .box
h = $this.find('img').height(); // Height of the image inside .box
$this.width(w).height(h); // Set width and height of .box to match image
});
Variant with same height of all blocks ( https://jsfiddle.net/br3t/fmovbtp1/ )
var classes = ["lg", "lg-in", "md"];
var requiredHeight = window.getComputedStyle(document.querySelector(".row2 .lg")).height;
classes.forEach(function(cls) {
document.querySelectorAll("." + cls).forEach(function(item) {
item.style.height = requiredHeight;
});
});

Using Json to load all images from server, and displaying them Masonry

What I'm trying to do is get 20 or so images from a folder on the server and display them using masonry.desandro and once scrolled to the bottom it will load another set of 20 images. Just like pinterest.
Currently it does load the images 20 at a time, the only problem I'm having is the first 20 display Masonry but when the next 20 load they aren't displaying Masonry
HTML
<div class="grid">
</div>
Json
$(document).ready(function() {
// The max number of images to be loaded at a time.
var limit = 16;
// JSON data will be assigned to this
var images = "";
// to remember where in JSON we are
// initialize to the value of limit - so that we can load in images
// before page scroll.
var currentIndex = limit;
// When there are fewer than `limit` images left, this
// value will be the difference between the current index
// and the length of the images array.
var stop = limit;
var grid = $(".grid");
// Make a GET request to the api
$.getJSON("***********************/newsite/api.php", function(data) {
// save the data to be used later.
images = data.weddingCakes;
console.log(data);
})
// create the first round of images.
.done(function() {
var html = "";
for (var i = 0; i < limit; i++) {
html += '<div class="grid-item"><img src="' + images[i] + '"></div>';
}
grid.append(html)
.masonry({
gutter: 3,
itemSelector: '.grid-item',
animate: true
});
console.log("masonry")
})
.error(function() {
console.log("error");
});
$(document).scroll(function() {
// get the scoll position with support for IE
// see http://jsbin.com/egegu3/6/edit?html,js,output
// for original code.
var totalHeight, currentScroll, visibleHeight;
if (document.documentElement.scrollTop) {
currentScroll = document.documentElement.scrollTop;
} else {
currentScroll = document.body.scrollTop;
}
totalHeight = document.body.offsetHeight;
visibleHeight = document.documentElement.clientHeight;
// only load more images if the scroll bar is at the bottom
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
var diff = images.length - currentIndex;
// if the difference is > 0 then there are more images in the array
if (diff > 0) {
stop = diff > limit ? limit : diff;
getImages(currentIndex, stop);
currentIndex += stop;
}
// otherwise, reset the index before calling getImages()
else {
currentIndex = 0;
stop = diff > limit ? limit : diff;
getImages(currentIndex, stop);
currentIndex += stop;
}
}
});
});
// gets the path for each image from index to stop
function getImages(index, stop) {
var html = "";
// create the img tags.
for (var i = index; i < index + stop; i++) {
html += '<div class="grid-item"><img src="' + images[i] + '"></div>';
}
var str = $(html);
grid.append(html).masonry("appended", str);
}
});
My JSfiddle
you were almost correct just missed a small part while reading documentation, here while appending elements you need to append HTML elements and pass same to the masonry function.
You were adding string to append and later on you were passing element to the masonry, Also this code -> var str = $(html); returns Array of HTML elements rather than string, so you need to add these elements to the grid and pass it to masonry
so your little change would be...
// gets the path for each image from index to stop
function getImages(index, stop) {
var html = "";
// create the img tags.
for (var i = index; i < index + stop; i++) {
html += '<div class="grid-item"><img src="' + images[i] + '"></div>';
}
var str = $(html);
grid.append(str).masonry("appended", str); // This line is a change
}
I have dummy fiddle for this as well

How do you use increments?

I am not sure how to use increments.
through a function. i can't get the paragraph to show the array words
<p id= "demo"
var Array = ["hello", "goodbye"];
var mimg = document.getElementById(imageArray[0]);
mimg.setAttribute('src', [index]);
//var ArrayIndex = 0;
function change() {
("src", Array[Index]);
imageIndex++;
if (Index >= Array.length) {
Index = 0;
}
}
Don't forget to use your browser's console, read this article Using Your Browser to Diagnose JavaScript Errors.
Don't use setattribute function, use src attribute.
var myImage = document.getElementById("mainImage");
var imageArray = ["http://lorempixel.com/400/200/sports/1/", "http://lorempixel.com/400/200/sports/2/", "http://lorempixel.com/400/200/sports/3/", "http://lorempixel.com/400/200/sports/4/"];
myImage.src = imageArray[0];
var imageIndex = 0;
function changeImage() {
myImage.src = imageArray[imageIndex];
imageIndex++;
if (imageIndex >= imageArray.length)
imageIndex = 0;
}
window.onload = function() {
setInterval(function() {
changeImage();
}, 1000);
};
<img id="mainImage" />
var myImage = document.getElementById("mainImage");
var imageArray = ["images/1.png","images/2.png","images/3.png","images/4.png"];
var mimg=document.getElementById(imageArray[0]);
mimg.setAttribute('src',photos[index]);
You aren't showing your relevant HTML, but I notice in this section you are getting an element with ID "images/1.png" and setting the src of that element to the value of something in photos[index]. You haven't shown how the photos array is loaded. Do you actually have an element with an ID "images/1.png"?
In your function, you set the src of the mainImage to the values in imageArray rather than the values in the photo array. That may be valid, but since that is different than what you did outside the function, I want to make sure that was intended.
I think you are talking about such solution:
var imageArr=["images/1.png", "images/2.png", "images/3.png", "images/4.png"];
$('#button'). on('click',function(){
var index=(Math.random(0,imageArr.length)*10)
$('#img').attr('src',imageArr[index])
});
Again you question is not clear, thus I think this will help you to get direction.
This should be solution if you are using plain JavaScript
var myImage = document.getElementById("mainImage"),
imageArray = ["images/1.png", "images/2.png", "images/3.png", "images/4.png"],
imageArrayIndex = 0;
myImage.src = imageArray[imageArrayIndex++];
function changeImage () {
myImage.src = imageArray[imageArrayIndex++];
imageArrayIndex = imageArrayIndex >= imageArray.length ? 0 : imageArrayIndex;
}
Make sure that your element is defined as "img".
Here's a solution which sets a data-index attribute on the image to keep track of the selected index. This solution is compatible with down to IE8 and does not use the Jquery library. Run the code snippet below for a test (click the image to go to the next one).
var mimg = document.getElementById('main-image'),
simg = document.getElementById('sec-image')
imgArr = [
'http://placehold.it/50x50/00AAAA',
'http://placehold.it/50x50/AAAA00',
'http://placehold.it/50x50/AA00AA',
];
var loopImages = function(element, imgArray, startAt) {
var index = element.getAttribute('data-index'),
newIndex = 0;
if (!index)
newIndex = ((startAt && startAt < imgArr.length-1) || 0) + 1;
else if (index < imgArr.length-1)
newIndex = parseInt(index) + 1;
element.setAttribute('data-index', newIndex);
element.src = imgArr[newIndex];
};
mimg.addEventListener('click', function(e) {
loopImages(e.target || e.srcElement, imgArr);
});
setInterval(function() {
loopImages(simg, imgArr);
}, 500);
<p>Preview (click to change)</p>
<img id="main-image" src="http://placehold.it/50x50/00AAAA">
<br>
<p>Preview with interval</p>
<img id="sec-image" src="http://placehold.it/50x50/00AAAA">

Add html code to a dynamically generated div

I have a js question that annoys me for the last couple of days.
i have a parallax template, where the parallax elements are generated automatically from js file.So i can add css style like transitions etc., but i would like to add some links on top of the divs, or some kind of on clik events.
What i think i have to look so far is in this fille (where the id of the divs are created):
enter //Parallax Element 2
var item = {};
item.name = "#tree21";
item.stackOrder = 1;
item.content = "image";
item.image = "images/parallax/bg2.png";
item.sizes = {w:"350",h:"350"};
item.screenPos = ["40%","-100%","300%","-115%"];
item.visibility = ["true","true","true","true"];
item.parallaxScene = true;
item.bPos = 200;
item.mouseSpeed = 15;
items.push(item);
and here (where i think the divs are generated
createScenes: function () {
//Resize Parallax Elements if responsive
if (responsive) {
var screenProp = this.maxWidth / 1920;
} else {
var screenProp = 1;
}
for (var i = 0; i < items.length; i++) {
if (jQuery(items[i].name).length == 0) {
jQuery("#parallax-container").append("<div id='" + items[i].name.substring(1, (items[i].name.length)) + "' class='parallaxItem'></div>");
}
Thank you!
Store a reference to your new div:
var div = jQuery("<div id='"
+ items[i].name.substring(1, (items[i].name.length))
+ "' class='parallaxItem'></div>")
.appendTo(jQuery("#parallax-container"));
jQuery(div).append('...');

JavaScript increment images

I'm trying to use JavaScript to list images 01-40 in order automatically.
Like this:
<img src="01.jpg" />
<img src="02.jpg" />
<img src="03.jpg" />
<img src="04.jpg" />
<img src="05.jpg" />
...
I don't want to write each img src manually, as I want to use this on multiple pages
I'd like the image starting and ending number to be variables that I can edit easily.
You need the parent element for imgs:
for ( var i = FIRST_NUMBER ; i < LAST_NUMBER ; i++ ) {
var elem = document.createElement("img");
if ( i < 10 ) {
elem.setAttribute("src", "0"+i+".jpg");
} else {
elem.setAttribute("src", i+".jpg");
}
document.getElementById(PARENT_ID).appendChild(elem);
}
function img_create(startIndex, endIndex) {
for (i = startIndex; i <= endIndex; i++) {
var oImg=document.createElement("img");
oImg.setAttribute('src', i+".jpg");
//other attributes you need
document.body.appendChild(oImg);
}
}
Working example: http://jsfiddle.net/Lw3bjcx4/1/
function createImages(count, elementId) {
// Get the container element where you want to create the images
var element = document.getElementById(elementId)
// Loop count times over to create count image elements
for (var i = 0 ; i < count ; i++) {
// Create a new image element
var imageElement = document.createElement('img')
// Set the source to index.jpg where index is 0,1,2,3.... count
imageElement.setAttribute('src', i + ".jpg")
// Append the new image element to the choosen container.
element.appendChild(imageElement)
}
}
// Test to create 10 images.
createImages(10,"imgs")
You can use like this:
var imgdiv = document.getElementById('imgdiv');
var img = imgdiv.getElementsByTagName('img');
for(var i=0;i<40;i++){
img[i].src=i+'.jpg';
}
Here is an alternative to all other answers, where you don't need to use an id to put images in. Just paste the script tag where you need to have the images. For example, if you put it in a div, the script will automatically insert the images in place.
<script type="text/javascript">
var thisScriptNode = document.currentScript;
for(var i = 1 ; i <= 40 ; i++) {
var img = document.createElement("img");
img.src = ("00" + i).substr(-2) + ".jpg";
thisScriptNode.parentNode.insertBefore(img, thisScriptNode);
}
</script>
You can easily change the number of leading zeros. For example, to get numbers with three characters, replace "00" with "000" and -2 with -3.
var to = 10;
var from = 0;
for (i = from; i < to; i++){
var elem = new Element('img', { src: i + '.jpg' });
document.body.appendChild(elem);
}
it will append to <body> images with names from 0.jpg to 9.jpg

Categories