Javascript in html tags to avoid repetition - javascript

I am a newbie to JavaScript and I need to use it with bootstrap for my own web page. My question is now how can I make a loop so that pictures names (stored as an array) can emerge in the right places of the HTML code so I do not have to copy the blocks of code for each picture.
For example :
<div class="row">
<div class="col-md-3 col-xs-6 portfolio-item">
<img class="img-responsive" src="01.jpg">
</div>
</div>
<div class="row">
<div class="col-md-3 col-xs-6 portfolio-item">
<img class="img-responsive" src="01.jpg">
</div>
</div>
<div class="row">
<div class="col-md-3 col-xs-6 portfolio-item">
<img class="img-responsive" src="02.jpg">
</div>
</div>
<div class="row">
<div class="col-md-3 col-xs-6 portfolio-item">
<img class="img-responsive" src="03.jpg">
</div>
</div>
As we can see here the only different text is the src.How can I store the names (paths) in an array and make a loop that changes the src property?
Thank you!

Try this demo: http://jsbin.com/pinoxeqapi/1/edit?html,output
I think that's what you're looking for.
CODE
$(function () {
var images = ["01.jpg", "01.jpg", "02.jpg", "03.jpg"];
$.each(images, function (index, element) {
var imgContainer = "<div class='row'><div class='col-md-3 col-xs-6 portfolio-item><img class='img-responsive' src='" + element + "'></div></div>";
$("body").append(imgContainer);
});
});

First Include JQuery (If not)
<script>
var srcArray = ['01.jpg', '02.jpg', '03.jpg', '04.jpg'];
$(document).ready(function () {
for (var i = 0; i < srcArray.length; i++) {
$('div.row img.img-responsive').eq(i).attr("src", srcArray[i]);
}
});
</script>

I would recommend using one of the templating frameworks described in some of the other answers. If you're interested to see how to implement this in pure JS:
var temp = document.querySelector('#portfolio-item-template');
['01.jpg', '02.jpg', '03.jpg', '04.jpg'].forEach(function(src) {
temp.content.querySelector(".img-responsive").src = src;
var newImg = document.importNode(temp.content, true);
document.querySelector('#insertion-point').appendChild(newImg);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<template id="portfolio-item-template">
<div class="row">
<div class="col-md-3 col-xs-6 portfolio-item">
<img class="img-responsive">
</div>
</div>
</template>
<div id="insertion-point">
</div>

You can use a template stored in the HTML and then generate the actual elements using an array of the image sources. Something like John Resig's micro-templates can achieve this.
<script type="text/template" id="img-tmpl">
<div class="row">
<div class="col-md-3 col-xs-6 portfolio-item>
<img class="img-responsive" src="<%= src %>">
</div>
</div>
</script>

Related

Handlebars lookup to make an href

I am trying to make a mod on an existing app. All I want to do is create an href that contains a url, but using the handlebars lookup function. When I try it just returns a blank value.
Here is my function:
var cardLink = function generateCardLink() {
var url = `"url/container-scan-reports/${vendor}/${product}/${image}"`
return url;
}
//...
res.render('vendor', {
title: 'Vendor Images',
images: images,
tags: tags,
cardLink: cardLink
});
I am then trying to pass in href this way on the top div of template.
<div class="row row-cards-pf ">
{{#each images}}
<div href={{lookup ../cardLink #index }} class="col-xs-12 col-sm-6 col-md-4 col-lg-4">
<div class="card-pf card-pf-view card-pf-view-select card-pf-view-single-select">
<div class="card-pf-body">
<div class="card-pf-top-element">
<span class="pficon-image card-pf-icon-circle"></span>
</div>
<h2 class="card-pf-title text-center">
{{ this }}
</h2>
<div class="card-pf-items text-center">
<div class="card-pf-item">
{{{ lookup ../tags #index}}}
</div>
</div>
<!-- <p class="card-pf-info text-center"><strong>Most recent image</strong> {{ lookup ../mostRecentImages #index}}</p> -->
</div>
<div class="card-pf-view-checkbox">
<input type="checkbox">
</div>
</div>
</div><!-- /col -->
{{/each}}
Can anyone help me?
You don't need lookup in this case. I think you want to display the url, so #index is not the right reference. Try it this way:
<div href={{../cardLink}} class="col-xs-12 col-sm-6 col-md-4 col-lg-4">

Replace class name on window resize

Here is my Markup. I want to update/replace class name col-sm-3
to col-md-6 on widow resize (ex: width < 800)
<div class="llotherlogos-userthumb">
<div class="col-sm-3">
<div class="logo-thumb">
<img class="img-fluid" src="images/logos/logo-seven.jpg" alt="">
<div class="logo-caption">
<div class="ll-category">Business</div>
<div class="ll-price"><span>1000BDT</span>5000 BDT</div>
</div>
</div>
</div>
<div class="col-sm-3">
<div class="logo-thumb">
<img class="img-fluid" src="images/logos/logo-eight.jpg" alt="">
<div class="logo-caption">
<div class="ll-category">Business</div>
<div class="ll-price"><span>1000BDT</span>5000 BDT</div>
</div>
</div>
</div>
<div class="col-sm-3">
<div class="logo-thumb">
<img class="img-fluid" src="images/logos/logo-nine.jpg" alt="">
<div class="logo-caption">
<div class="ll-category">Business</div>
<div class="ll-price"><span>1000BDT</span>5000 BDT</div>
</div>
</div>
</div>
<div class="col-sm-3">
<div class="logo-thumb">
<img class="img-fluid" src="images/logos/logo-ten.jpg" alt="">
<div class="logo-caption">
<div class="ll-category">Business</div>
<div class="ll-price"><span>1000BDT</span>5000 BDT</div>
</div>
</div>
</div>
</div>
JavaScript
var otherlogos = function(){
var ww = document.body.clientWidth;
var myLogos = document.querySelectorAll(".llotherlogos-userthumb .col-sm-3");
if(ww < 800){
myLogos.className.replace(col-sm-3, col-md-6);
}
}
window.onresize = otherLogos;
You need this:
myLogos.className.replace(col-sm-3, col-md-6);
To be:
myLogos[0].classList.replace('col-sm-3', 'col-md-6');
(querySelectorAll returns an array of elements, even if only one element matches, hence the need for myLogos[0].)
To do this for multiple elements, you'd need something like this (explicit for loop, because I think foreach doesn't work here):
for (let i = 0; i < myLogos.length; ++i)
myLogos[i].classList.replace('col-sm-3', 'col-md-6');
with jQuery you could do something like this
<script>
$(window).resize(function () {
if($(window).width()<800){
$('.llotherlogos-userthumb').children().removeClass('col-sm-3').addClass('col-md-6');
}else{
$('.llotherlogos-userthumb').children().removeClass('col-md-6').addClass('col-sm-3');
}
});
</script>
You just require to use toggle for achieving the goal. The example is given below:
myLogos.classList.toggle('col-sm-3');
myLogos.classList.toggle('col-md-6');
or
var myLogos = document.querySelectorAll(".llotherlogos-userthumb .col-sm-3");
var classes = myLogos.classList;
var result = classes.replace("col-sm-3", "col-md-6");
console.log(result);
For more info on above access this link
try this jquery code:
enter$( window ).resize(function() {
var ww = document.body.clientWidth;
<==========now select id or element==============>
$("#a1").addClass( "my-hidden").removeClass("my-disply");
// code here
});

Jquery .append .after how to format .each

I am trying to achieve the following:
<div class="item">
<div class="container-fluid">
<div class="row">
<div class="col-md-3">IMG</div>
<div class="col-md-9">TEXT</div>
</div>
</div>
</div>
<div class="item">
<div class="container-fluid">
<div class="row">
<div class="col-md-3">IMG</div>
<div class="col-md-9">TEXT</div>
</div>
</div>
</div>
Here is what I have so far:
var ws_ftr = data.ws_ftr.records;
console.log(JSON.stringify(ws_ftr));
jQuery.each(ws_ftr, function(index, ftr) {
jQuery('.carousel-inner').append('<div class="item">');
jQuery('.item').append('<div class="container-fluid">');
jQuery('.container-fluid').append('<div class="row">');
jQuery('.row').append('<div class="col-md-3"><img src="img/features_sliding/'+ftr[3] +'" alt="feature-'+ftr[2]+'"/></div><div class="col-md-9"><h2>'+ftr[2]+'</h2>'+ftr[1]+'</div>');
Which gives me this, I stopped at the first major error because I believe the others will be corrected once I fix it...
<div class="item">
<div class="container-fluid">
<div class="row">
<div class="col-md-3">IMAGE</div>
<div class="col-md-9">TEXT</div>
**<div class="col-md-3">IMG</div>
<div class="col-md-9">TEXT</div>**
This should not be giving me the col-md-3 and col-md-9 for each loop, but instead should be giving me the entire item block.
I am fairly new to jQuery/javascript and am learning as I go. Can anyone explain to me what I have done wrong and the best way to correct? Thanks so much!
1.Instead of multiple .append() do every-thing in single .append()
2.Close all the div's that you started.
jQuery('.carousel-inner').append('<div class="item"><div class="container-fluid"><div class="row"><div class="col-md-3"><img src="img/features_sliding/'+ftr[3] +'" alt="feature-'+ftr[2]+'"/></div><div class="col-md-9"><h2>'+ftr[2]+'</h2>'+ftr[1]+'</div></div></div></div>');
Note- seems that non-closed divs are creating the issue.
Just noted that in your jQuery you never closed your any of your divs. So continuing with your code it can be completed like so:
var ws_ftr = data.ws_ftr.records;
console.log(JSON.stringify(ws_ftr));
$.each(ws_ftr, function(index, ftr) {
$('.carousel-inner').append('<div class="item">');
$('.item').append('<div class="container-fluid">');
$('.container-fluid').append('<div class="row">');
$('.row').append('<div class="col-md-3"><img src="img/features_sliding/'+ftr[3] +'" alt="feature-'+ftr[2]+'"/></div><div class="col-md-9"><h2>'+ftr[2]+'</h2>'+ftr[1]+'</div>');
$('.container-fluid').append('</div>');
$('.item').append('</div>');
$('.carousel-inner').append('</div>');
);
I believe this can also be completed this way:
var ws_ftr = data.ws_ftr.records;
console.log(JSON.stringify(ws_ftr));
$.each(ws_ftr, function(index, ftr) {
$('.carousel-inner').append('<div class="item"></div>');
$('.item').append('<div class="container-fluid"></div>');
$('.container-fluid').append('<div class="row"></div>');
$('.row').append('<div class="col-md-3"><img src="img/features_sliding/'+ftr[3] +'" alt="feature-'+ftr[2]+'"/></div><div class="col-md-9"><h2>'+ftr[2]+'</h2>'+ftr[1]+'</div>');
);

Change Image on div onclick()

I want to load different image on different div clicks. How do I know which div is clicked? Do I have to pass the div class as argument?
<script type="javascript">
function ChangeLibaas() {
}
</script>
<div class="Indeximages">
<img src="images/white.png" id="libaasImage" class="img-responsive jubbahImage" alt="" />
</div>
<div class="col-md-12 nopadding customTabs">
<h2>Pick a Colour</h2>
<div class="col-md-3 colourBlue" onclick="ChangeLibaas()"></div>
<div class="col-md-3 colourBlack" onclick="ChangeLibaas()"></div>
<div class="col-md-3 colourGreen" onclick="ChangeLibaas()"></div>
</div>
Simplest inline: pass (this):
<div class="col-md-3 colourBlue" onclick="ChangeLibaas(this)"></div>
and use it :
function ChangeLibaas(theClickedDiv) {
var img = "images/"+
theClickedDiv.className.split("colour")[1].toLowerCase()+".png"; // take the colour
document.getElementById("libaasImage").src=img;
}
To make it all neater, use an attribute and unobtrusive code
window.onload=function() {
var divs = document.querySelectorAll("div.col-md-3");
for (var i=0;i<divs.length;i++) {
divs[i].onclick=function() {
document.getElementById("libaasImage").src="images/"+
this.getAttribute("data-color")+".png";
}
}
}
using
<div class="col-md-3 colourBlue" data-color="blue""></div>
You can pass as an argument, like this:
<div class="col-md-12 nopadding customTabs">
<h2>Pick a Colour</h2>
<div class="col-md-3 colourBlue" onclick="ChangeLibaas(this)"></div>
<div class="col-md-3 colourBlack" onclick="ChangeLibaas(this)"></div>
<div class="col-md-3 colourGreen" onclick="ChangeLibaas(this)"></div>
</div>
And then:
<script type="javascript">
function ChangeLibaas(sender) {
var div = sender;
}
</script>
But it's better if you use event listeners.
I hope it can be useful:
In your html
<div class="Indeximages">
<img src="images/white.png" id="libaasImage" class="img-responsive jubbahImage" alt="" />
</div>
<div class="col-md-12 nopadding customTabs">
<h2>Pick a Colour</h2>
<button class="col-md-3" data-color="colourBlue" onclick="ChangeLibaas(this)">Blue</div>
<button class="col-md-3" data-color="colourBlack" onclick="ChangeLibaas(this)">Black</div>
<button class="col-md-3" data-color="colorGreen" onclick="ChangeLibaas(this)">Green</div>
</div>
In javascript, code looks like:
function ChangeLibaas(origin) {
var color = origin.dataset.color;
var img = document.getElementById('libaasImage');
img.src = color + ".jpg";
}

Bootstrap different col-* with ng-repeat

I've got a movie reviews example application built in angular + bootstrap, I'm trying to build a "grid" of 3 images for medium and up screens, the problem is that when I want to have only 2 images per row for xs screens.
I'm using ng-repeat and populating the imgs inside the cols.
is there a nice way to do this? (I'm aware that the $index + N may be out of bounds, and that there is code duplication here. just want to find a good solution for rearranging the bootstrap grid for different screen sizes on dynamic data)
<div ng-repeat="movie in movies" ng-if="$index % 3 == 0" class="row slide-left">
<div class="col-md-4">
<img ng-src='http://image.tmdb.org/t/p/w185/{{movies[$index].poster_path}}' ng-click="chooseMovie(movies[$index])">
</div>
<div class="col-md-4">
<img ng-src="http://image.tmdb.org/t/p/w185/{{movies[$index + 1].poster_path}}" ng-click="chooseMovie(movies[$index + 1])">
</div>
<div class="col-md-4">
<img ng-src="http://image.tmdb.org/t/p/w185/{{movies[$index + 2].poster_path}}" ng-click="chooseMovie(movies[$index + 2])">
</div>
</div>
<div ng-repeat="movie in movies" >
<div class="col-md-4 col-xs-6">
<img ng-src='http://image.tmdb.org/t/p/w185/{{movie.poster_path}}' ng-click="chooseMovie(movie)">
</div>
</div>
This should do the trick.
I removed the row but i think even with it will works unless you use the clearfix class.
The grid will automatically go on the next line after "12" columns.
So a size of 4 for medium screen means 3 per line, 6 for xs screen ->2/line :)
You can detect bootstrap columns by using the following function:
function findBootstrapEnvironment() {
var envs = ["ExtraSmall", "Small", "Medium", "Large"];
var envValues = ["xs", "sm", "md", "lg"];
var $el = $('<div>');
$el.appendTo($('body'));
for (var i = envValues.length - 1; i >= 0; i--) {
var envVal = envValues[i];
$el.addClass('hidden-'+envVal);
if ($el.is(':hidden')) {
$el.remove();
return envs[i]
}
};
}
The setting a value to the scope based on the return
if(findBootstrapEnvironment()==="Medium"|(findBootstrapEnvironment()==="Large"|){
$scope.size="Medium"
}else{
$scope.size="Small"
}
And then with ng-if you can manage the div to be with 3 or 2 photos like this
Three photos if medium
<div ng-repeat="movie in movies" ng-if="size==medium" class="row slide-left">
<div class="col-md-4">
<img ng-src='http://image.tmdb.org/t/p/w185/{{movies[$index].poster_path}}' ng-click="chooseMovie(movies[$index])">
</div>
<div class="col-md-4">
<img ng-src="http://image.tmdb.org/t/p/w185/{{movies[$index + 1].poster_path}}" ng-click="chooseMovie(movies[$index + 1])">
</div>
<div class="col-md-4">
<img ng-src="http://image.tmdb.org/t/p/w185/{{movies[$index + 2].poster_path}}" ng-click="chooseMovie(movies[$index + 2])">
</div>
</div>
Two photos if small
<div ng-repeat="movie in movies" ng-if="size==small" class="row slide-left">
<div class="col-sm-4">
<img ng-src='http://image.tmdb.org/t/p/w185/{{movies[$index].poster_path}}' ng-click="chooseMovie(movies[$index])">
</div>
<div class="col-sm-4">
<img ng-src="http://image.tmdb.org/t/p/w185/{{movies[$index + 1].poster_path}}" ng-click="chooseMovie(movies[$index + 1])">
</div>
</div>

Categories

Resources