How to create an array of divs with content? - javascript

I'm trying to create an array of nested divs, in which I only need to change 3 values when writing the divs to the document (html).
My divs look like this:
<div class="item">
<div class="item-h"> <a class="item-anchor" href="1_water_bottle.html">
<div class="item-image"> <img class="item-image-first" src="images/img_1_water_bottle.png" alt="">
<div class="item-meta">
<h2 class="title">Water Bottle 1</h2>
<span class="item-arrow"></span> </div>
</div>
</a> </div>
</div>
I need to create an array of about 50 items, and then use the document.write function to write 4 of those arrays for each page, as a section for "similar stuff".
I searched on stackoverflow, and came up with :: this page :: , which explains how to create an array in javascript, and then found another script that uses the document.write function.
The script uses an array of categories, to populate a form selection. And it does so, but using an array : (var categories = new Array("a1", "a2", "a3", ...) and so on.
for(var hi=0; hi<categories.length; hi++)
document.write("<option value=\""+categories[hi]+"\">"+categories[hi]+"</option>");
Could I use these two scripts to populate a section with 4 items from the array of the divs?
If so, then how could I do it? I know it can be done in php, but don't know if this can be done in javascript.
I tried, and created this array in notepad++, but the code wasn't recognized as a string, per array element...
var array_divs = [
$('<div class="item">
<div class="item-h"> <a class="item-anchor" href="1_water_bottle.html">
<div class="item-image"> <img class="item-image-first" src="images/img_1_water_bottle.png" alt="">
<div class="item-meta">
<h2 class="title">Water Bottle 1</h2>
<span class="item-arrow"></span> </div>
</div>
</a> </div>
</div>') ,
$('<div class="item">
<div class="item-h"> <a class="item-anchor" href="1_water_bottle_2.html">
<div class="item-image"> <img class="item-image-first" src="images/img_1_water_bottle_2.png" alt="">
<div class="item-meta">
<h2 class="title">Water Bottle 2</h2>
<span class="item-arrow"></span> </div>
</div>
</a> </div>
</div>')
]
Trying to populate the section, with selective items from the array, for example:
document.write(array_divs[1],array_divs[2]);
I haven't tried this, but since notepad++ didn't treat my div as a string, I had to search again... but couldn't find any info regarding this.
Thanks for any help.
-

Related

Add a Like + Sort Function to existing dynamic funcion

I wrote a function that dynamically creates a webpage for me based on a json database.
Now I want to add 2 functions:
If you click the like img (its got the id button) the like counter should increase on the webpage by 1. Pretty easy just a on(click) with jQuery variable++ and then .text(variable)
A sort function - based on the likes one item received, you should be able to sort it (most liked div first, 2nd, 3rd....
I can write it for each individually with individual variables when I give all the like buttons and outputs a separate id but I wanted to make it dynamic so if you add new data to json file it dynamically works with the like and sort function.
The likes are not saved anywhere for now.
Since sitting on it for 3h and google so much and so much stackoverflow I think I overloaded my brain with different stuff and now nothing seems to work ^^
function filmInsert(insert) {
$.each(film, function(i, data) { //.each statt loop
let box =
`<div class="boxwrapper">
<div class="imgbox">
<img src="${data.img}" alt="${data.titel}">
</div>
<div class="textbox">
<h3>${data.titel}</h3>
<p>${data.beschreibung}</p>
<p> <a id="button${data.id}">
<img src="img/budspencer_official.png"> Like
</a>
<span class="output${data.id}">${data.likes}</span>
</p>
</div>
</div>`;
insert.append(box);
});
}
I've added a container element for the boxwrapper items as I assume you have one and as it's better to have one instead of just adding the sorted items to the body of the HTML document.
$(document).on("click", ".textbox a", function() {
let likes = parseInt($(this).closest(".textbox").find("span").text());
$(this).closest(".textbox").find("span").text(likes + 1);
});
$("#sort").on("click", function() {
let divs = $(".boxwrapper")
let sorted = divs.sort(function(a, b) {
return $(a).find("span").text() < $(b).find("span").text() ? 1 : -1;
});
$(".container").html(sorted);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="boxwrapper">
<div class="imgbox">
<img src="example.gif" alt="Title">
</div>
<div class="textbox">
<h3>Titel</h3>
<p>Description</p>
<p> <a id="button1">
<img src="https://dummyimage.com/40x40/000/fff&text=1"> Like
</a>
<span class="output1">0</span>
</p>
</div>
</div>
<div class="boxwrapper">
<div class="imgbox">
<img src="example.gif" alt="Title">
</div>
<div class="textbox">
<h3>Titel 2</h3>
<p>Description 2</p>
<p> <a id="button2">
<img src="https://dummyimage.com/40x40/000/fff&text=2"> Like
</a>
<span class="output2">0</span>
</p>
</div>
</div>
</div>
<button id="sort">
Sort
</button>

removing and adding a class based on position within an array Angular

I am creating a blog page using angular 5 where each of the blog posts have the class:
col-md-4
However, what I want is the latest blog post (i.e the first on the page) to have the class of :col-md-12.
The html that I have is as follows:
<div *ngFor="let blog of blogs" class="blog-posts col-md-4">
<div class="card">
<img class="blog-img" (click)="goToBlogDetailsPage(blog.sys.id)"src="{{blog.fields.blogimage.fields.file.url}}" class="rounded" alt="">
<div class="info">
<h3 class="author">{{blog.fields.authorInfo}}</h3>
<h2 (click)="goToBlogDetailsPage(blog.sys.id)" class="title">{{blog.fields.title}}</h2>
<p class="short-desc" > {{blog.fields.desciption}}</p>
<img (click)="goToBlogDetailsPage(blog.sys.id)" class="sml-logo" src="/assets/img/logos/logo_blue.png" alt="">
<!-- <button (click)="goToBlogDetailsPage(blog.sys.id)"class="btn btn-info">Open Blog Post</button> -->
</div>
</div>
</div>
</div>
</div>
I have tried accessing the index of the array[0] however I can not seem to alter the styling on just the first item, any suggestions?
Use index and ternary operator to set the class
<div *ngFor="let blog of blogs; let ind = index" class="blog-posts"
[ngClass]="ind === 0 ? 'col-md-12' : 'col-md-4'" >

How can show <div> and <a> in ascending order when page loads using jquery?

I have some listings. At present when page loads listing is showing like
Img 1
Test 1
Img 3
Test 3
img 2
Test 2
When page loads, I need results like
Img 1
Test 1
Img 2
Test 2
Img 3
Test 3
Img is in <a> tag and test content is in <div> tag
How can order the <div> and <a> in ascending order when page loads?
In <div> tag there is data-id. In <a> tag there is data-tag-id.
Html
<figure class="image_container">
<img src="files/maier-energie-umwelt/produkte/phantom-ruehrwerke/Phantom-1400.jpg" alt="" width="738" height="800">
<figcaption class="caption">
<a class="area center-bg hasDescription" href="javascript:void(0)" title="Verschleißfester Propeller aus PA12" data-description-id="areaDesc-1" style="width: 6.775%;height: 18.75%;left: 14.228%;top: 1.25%;background-image: url(files/maier-energie-umwelt/layout/marker.png);" data-tag-id="1"></a>
<div id="areaDesc-1" class="description invisible" data-id="1" style="display: block;"><p><strong>Test1</p></div>
<a class="area center-bg hasDescription" href="javascript:void(0)" title="Abgedeckte doppelte Gleitringdichtung" data-description-id="areaDesc-3" style="width: 6.775%;height: 18.75%;left: 25.745%;top: 21.875%;background-image: url(files/maier-energie-umwelt/layout/marker.png);" data-tag-id="3"></a>
<div id="areaDesc-3" class="description invisible" data-id="3"><p>Test3</p></div>
<a class="area center-bg hasDescription" href="javascript:void(0)" title="Optimierte Schutzschelle aus Edelstahl" data-description-id="areaDesc-2" style="width: 6.775%;height: 18.75%;left: 27.778%;top: 49.375%;background-image: url(files/maier-energie-umwelt/layout/marker-bottom.png);" data-tag-id="2"></a>
<div id="areaDesc-2" class="description invisible" data-id="2"><p>Test2</p></div>
</figcaption>
</figure>
Script
$('.description').sort(function (a, b) {
return parseInt(a.data-id) > parseInt(b.data-id);
}).each(function(){
var elem = $(this);
elem.remove();
$(elem).appendTo(".description");
});
Your code is close to be working.
You only need to use jQuery .data() to access data attribute value. Note that it returns number, not string, if data attribute stores numeric value, so you don't need to parse it yourself.
You also do not need to .remove() element. You just need to append your item to specific container - if item is already in DOM tree, then it will automatically be detached from its current place and will be moved it to a new location. Just appending items consequently in the right order gives the desired results.
$(".container > div")
.sort(function(a, b) { return $(a).data("id") - $(b).data("id"); })
.each(function() { $(this).appendTo(".container"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div data-id="1">1</div>
<div data-id="3">3</div>
<div data-id="2">2</div>
<div data-id="9">9</div>
<div data-id="5">5</div>
<div data-id="4">4</div>
<div data-id="8">8</div>
<div data-id="7">7</div>
<div data-id="6">6</div>
</div>
Update: in order to sort your divs together with related <a/> tags, you can use jQuery .prev() which simply takes the previous DOM element and then you can do the same operation with this link. However, it is a better idea to wrap a and div into single element, so that their relation is described in HTML, but not by their order.
$(".container > div")
.sort(function(a, b) { return $(a).data("id") - $(b).data("id"); })
.each(function() {
$(this).prev().appendTo(".container");
$(this).appendTo(".container");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
One
<div data-id="1">1</div>
Three
<div data-id="3">3</div>
Two
<div data-id="2">2</div>
Nine
<div data-id="9">9</div>
Five
<div data-id="5">5</div>
Four
<div data-id="4">4</div>
Eight
<div data-id="8">8</div>
Seven
<div data-id="7">7</div>
Six
<div data-id="6">6</div>
</div>
You can try:
var yourList = $(".description");
yourList.sort(function(x, y){
return $(x).data("id")-$(y).data("id")
});
$(".caption").append(yourList);
Have tested and works now, noticed a small typo. See it working here https://jsfiddle.net/trekmp/pLyw3qg4/5/

jquery: how to append DOM element to selector within variable containing other DOM elements

When storing DOM elements in a javascript variable prior to appending them to the actual DOM is there a way with jQuery to select elements inside the variable?
For example,
I have a list of tweets on my page. Every time I click a refresh button I append a new tweet to the list below.
I add the new tweet like follows:
new tweet
<li class="tweet normal-tweet" data-user-name="Dorothy">
<div class="image">
<img height="48" width="48" src="http://twitter.com/api/users/profile_image?screen_name=Dorothy" alt="" />
</div>
<div class="content">
<div class="user">
<a class="user-name" href="http://twitter.com/Dorothy" title="Dorothy">Dorothy</a>
<div class="full-name"></div>
</div>
<div class="text">Once in a lullaby</div>
<div class="time-stamp" data-time="1322631934000">1322631934000</div>
</div>
</li>
Inside each tweet on the page, not the new tweet yet, I use jQuery to append some elements.
I have:
var actionsMarkup =
"<div class='actions'>
<span class='favorite'>Favorite</span>
<span class='retweet'>Retweet</span>
<span class='reply'>Reply</span>
</div>";
and I append it to the element with the .content class
$(actionsMarkup).appendTo('#tweets .tweet .content');
Now, when I make a new tweet I do the following:
$(document).on('click', '.refresh', function() {
newTweet = $(<new tweet code from above>);
actionsMark = $(actionsMarkup);
$(newTweet.appendTo('#tweets');
I need to be able to append the actionsMark contents to the div with class .content. However, I can't just reapply my prior statement of
$(actionsMarkup).appendTo('#tweets .tweet .content');
because that puts the markup on all .content divs again, even if it is already there.
Is there a way for me to use selectors to access the DOM nodes in my newTweet variable before I append it to the document object?
I am thinking something like
$(actionsMarkup).appendTo( newTweet, '.content');
If there is no way with selectors to do this then what are some other quick ways?
List of Tweets and Tweet container
<ul id="tweets" class="normal-tweet show-promoted-tweets">
<li class="tweet promoted-tweet" data-user-name="Dorothy">
<div class="image">
<img height="48" width="48" src="http://twitter.com/api/users/profile_image?screen_name=Dorothy" alt="" />
</div>
<div class="content">
<div class="user">
<a class="user-name" href="http://twitter.com/Dorothy" title="Dorothy">Dorothy</a>
<div class="full-name">Dorothy</div>
</div>
<div class="text">Somewhere over the rainbow</div>
<div class="time-stamp" data-time="1322631934000">3 minutes ago</div>
</div>
</li>
<li class="tweet promoted-tweet" data-user-name="lion">
<div class="image">
<img height="48" width="48" src="http://twitter.com/api/users/profile_image?screen_name=lion" alt="" />
</div>
<div class="content">
<div class="user">
<a class="user-name" href="http://twitter.com/lion" title="lion">lion</a>
<div class="full-name">Lion</div>
</div>
<div class="text">Way up high,</div>
<div class="time-stamp" data-time="1322631934000">17 minutes ago</div>
</div>
</li>
<li class="tweet normal-tweet" data-user-name="scarecrow">
<div class="image">
<img height="48" width="48" src="http://twitter.com/api/users/profile_image?screen_name=scarecrow" alt="" />
</div>
<div class="content">
<div class="user">
<a class="user-name" href="http://twitter.com/scarecrow" title="scarecrow">scarecrow</a>
<div class="full-name">Scarecrow</div>
</div>
<div class="text">And the dreams that you dreamed of,</div>
<div class="time-stamp" data-time="1322631934000">32 minutes ago</div>
</div>
</li>
</ul>
You can use .last(), to select the last element after you append your new tweet, like below:
$(document).on('click', '.refresh', function() {
newTweet = $(<new tweet code from above>);
$(newTweet).appendTo('#tweets');
var actionsMarkup =
"<div class='actions'>
<span class='favorite'>Favorite</span>
<span class='retweet'>Retweet</span>
<span class='reply'>Reply</span>
</div>";
$("#tweets .tweet").last().find(".content").append(actionsMarkup);
});
if you insist to use appendTo(), you can try using :last-child:
$(actionsMarkup).appendTo('#tweets .tweet:last-child .content');
I was looking to see if you can do the same thing, found this question but the existing answer is not useful in my case as i would like to alter the element before adding.
You can create a new dom element in a variable with jQuery and do operations on it as if it is already in the dom before appending it.
Example:
var newTweet = $('<div></div>');
newTweet.addClass('tweet');
newTweet.append('<span class="username"></span>');
newTweet.find('span.username').html('John Doe');
$('body').append(newTweet);
the following will be appended to the body:
<div class="tweet"><span class="username">John Doe</span></div>
Very handy if you are building a reusable interface element (like a dialogue box) with multiple options.

how to double nest angular ng-repeat

I have a template which is constructed in the following way...
<div ng-repeat="itemEntry in itemEntry">
<!-- content -->
<section class="product-view-wrapper" ng-repeat="productView in itemEntry.Productview">
<div class="slide" ng-repeat="productImg in itemEntry.productImgs">
<img ng-src="{{productImgs.img}}"/>
</div>
<!-- Content -->
</section>
</div>
Is it possible to nest two repeats inside an ng-repeat? if so based on the example above is this the correct html method?
i also have a json file which looks like the following:
image: "http://www.colette.fr/media/push/swa_mmm_001255.jpg",
productTitle: "Ipath lowrunner",
productDesc: "Low skateshoes - Grey",
user: "knows",
price: "$17",
productImgs: [
{img: "http://www.colette.fr/media/push/swa_mmm_001255.jpg"},
{img: "http://www.colette.fr/media/push/paddin265.jpg"}
]
},
However i have noticed the productImg content does not appear when view through inspect element. Again is the correct structure when double nesting an ng-repeat function - if this even can be done?
click on demo for a more in depth example
You aren't repeating over the proper array within the nested repeat. I scaled your demo down to just relevant html for the question
<section class="product-view-wrapper" ng-repeat="productObject in itemEntry">
<!-- each loop of the <section> will output from productObject contained in itemEntry array -->
<h3>{{productObject.productDesc}}</h3>
<img ng-src="{{productObject.image}}" height="120px">
<h4>Repeating images</h4>
<!-- want to loop over array contained in each productObject -->
<div class="slide" ng-repeat="productImg in productObject.productImgs" style="float:left">
<img ng-src="{{productImg.img}}" height="80px" />
</div>
<hr style="clear:both">
</section>
DEMO

Categories

Resources