Jquery .append .after how to format .each - javascript

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>');
);

Related

Could I get to an element using two ids?

Here's my code:
<div id='layer1'>
<div id='a'>
<div id='b'>
<div id='layer2'>
<div id='a'>
<div id='b'>
<div id='layer3'>
<div id='a'>
<div id='b'>
I want to try to get the element [a] of layer1.
Could I do this using pure javascript and withOUT jquery and other stuff?
An ID uniquely identifies one single element on the page. The behavior you described is more like "a class" inside of an ID:
document.querySelector("#counter-for-drinks .up-arrow")
and so if you want a different up-arrow, it is:
document.querySelector("#counter-for-burgers .up-arrow")
document.querySelector() is what is similar to jQuery $(" "). It also has the form document.querySelectorAll() for getting all matched elements.
Your HTML is missing closing tags. You can always validate your code here.
Also, you should use class instead of id.
<div id='layer1'>
<div class='a'></div>
<div class='b'></div>
</div>
<div id='layer2'>
<div class='a'></div>
<div class='b'></div>
</div>
<div id='layer3'>
<div class='a'></div>
<div class='b'></div>
</div>
You can use javascript to get elements:
document.querySelector("#layer1 .a")
var firstA = document.querySelectorAll('#layer1 #a');
var nodeString = '';
if (firstA.length > 0) {
for (var i = 0; i < firstA.length; i++) {
nodeString = nodeString + firstA[i].innerText + '<br/>';
}
}
document.getElementById('founded-nodes').innerHTML = nodeString;
#founded-nodes {
color: brown;
}
<div id='layer1'>
<div id='a'>layer1 aaa</div>
<div id='b'>layer1 bbb</div>
</div>
<div id='layer2'>
<div id='a'>layer2 aaa</div>
<div id='b'>layer2 bbb</div>
</div>
<div id='layer3'>
<div id='a'>layer3 aaa</div>
<div id='b'>layer3 bbb</div>
</div>
<div id="founded-nodes"></div>
As all said in above over comments and answers, one must use a single id on the same page, or else the use of classes is a must. But if you want to achieve this, you can have a look at code.

anchor tag in not making div clickable

i am trying to make a whole div clickable, i did the following
<a href=""><div class="col-lg-3 col-md-6 col-sm-6 col-12 item-mb">
<div class="service-box1 bg-body text-center">
<img src="img/service/service1.png" alt="service" class="img-fluid">
<h3 class="title-medium-dark mb-none">Electronics</h3>
<div class="view">(19,805)</div>
</div>
</div></a>
but he div is not becoming clickable, can anyone please tell me whats wrong in my code?
Try
<div class="col-lg-3 col-md-6 col-sm-6 col-12 item-mb" onClick="javascript:window.location='//stackoverflow.com'">
<div class="service-box1 bg-body text-center">
<img src="img/service/service1.png" alt="service" class="img-fluid">
<h3 class="title-medium-dark mb-none">Electronics</h3>
<div class="view">(19,805)</div>
</div>
</div>
First of all, you can't have a div inside a. I mean, technically in some environments it works, but its against specification, so you can't rely on that structure. If you want to have a div wide link you better have your a absolutely positioned and stretched to fit your div
You can use javascript, in the code below I created a function that adds click event handlers instead of using a tags which can't be put inside each other.
Also included an example of how to style the div (see clickable css class).
function addLink(divId, url){
let div = document.getElementById(divId);
div.setAttribute('data-link-url', url);
link1.addEventListener('click', function(e){
window.location = this.getAttribute('data-link-url');
});
}
addLink('link1', 'https://stackoverflow.com');
.clickable{
cursor: pointer;
}
<div id="link1" class="clickable">
<div class="service-box1 bg-body text-center">
<img src="img/service/service1.png" alt="service" class="img-fluid">
<h3 class="title-medium-dark mb-none">text</h3>
<div class="view">(19,805)</div>
</div>
</div>

Moving returned data around from an ajax request with jQuery

I'm loading some information from a page. I want to move some of the content around and then load it up to a div in the corrected order. Here's what I mean. Imagine this is the content on the page being called:
<div class="wrapper">
<div class="product">some text
<div class="item" id="234"></div>
<div class="description>More text</div>
</div>
<div class="product">some text
<div class="item" id="3343"></div>
<div class="description">More text</div>
</div>
</div>
These are just showing two products, but imagine it's 30 or so products. Now when I load the page using an ajax call, I want to re-arrange some of the content before I place it in a div. My new content should look like this:
<div class="wrapper">
<div class="product">some text
<div class="description>More text
<div class="item" id="234"></div>
</div>
</div>
<div class="product">some text
<div class="description">More text
<div class="item" id="3343"></div>
</div>
</div>
</div>
So I took the "item" class and moved it into the description class. How do I accomplish this for all the products? It would look something like this I suppose:
$.get('/product-page',function(data){
$('#container').html($(data).MOVE-STUFF-AROUND);
});
Given this HTMl:
<div class="wrapper">
<div class="product">some text
<div class="item" id="1111"></div>
<div class="description">More text</div>
</div>
<div class="product">some text
<div class="item" id="2222"></div>
<div class="description">More text</div>
</div>
</div>
Running this JQuery code:
$(".product").each(function(i, obj) {
let $prodcut = $(this);
let $item = $prodcut.children(".item");
let $desc = $prodcut.children(".description");
$item.appendTo($desc);
});
Will give you this output:
<div class="wrapper">
<div class="product">some text
<div class="description">More text
<div class="item" id="1111"></div>
</div>
</div>
<div class="product">some text
<div class="description">More text
<div class="item" id="2222"></div>
</div>
</div>
</div>
The way it works: I select all prodcuts divs. I loop into each one and select the div labled "item" and then I move that div and append it into a div labled "description". Both item and description are children of product.
DEMO:
$(".product").each(function(i, obj) {
let $prodcut = $(this);
let $item = $prodcut.children(".item");
let $desc = $prodcut.children(".description");
$item.appendTo($desc);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<div class="wrapper">
<div class="product">some text
<div class="item" id="1111"></div>
<div class="description">More text</div>
</div>
<div class="product">some text
<div class="item" id="2222"></div>
<div class="description">More text</div>
</div>
</div>
Hard to tell from what is shown what you actually get as response. Assuming it is the full wrapper do:
$.get('/product-page',function(data){
var $data = $(data);
$data.find('.description').append(function() {
return $(this).prev('.item');
});
$('#container').html($data);
});
DEMO
I presume /product-page returns HTML since you suggest displaying it using $('#container').html(data);. If so, you can arrange your HTML in the backend script (product-page) so when you call it on AJAX, the HTML data is ready.
Or, you can opt /product-page to return JSON data, then arrange it in your JS code, e.g.:
$.get('/product-page', function(data) {
$('.wrapper').html(''); // assuming you want to clear contents of .wrapper
$.each(data, function (v) {
var html = '<div class="product>"' + v.some_text;
html += '<div class="description"'> + v.more_text;
html += '<div class="item">' + v.item_details + '</div>';
html += '</div>';
html += '</div>';
$('.wrapper').append(html);
});
});
EDIT:
Comments were already added before I could submit my answer, and realized above won't answer the OP, as AJAX endpoint comes from third party.
If the data comes from a third party, you need to create a DOM manipulator function based on your needs. Sadly, the construct depends on your needs.

Javascript in html tags to avoid repetition

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>

Unable to use $.after() to close a div tag

This problem is best illustrated by example:
http://jsbin.com/lavonexuse
The desired effect is for clicking "Insert Row" to insert a full-width row after the indicated column (indicated by the class .insertion-point). The problem I'm running into is that instead of closing the current row first, and starting a new one, it just embeds a new row within the main row.
How do I close out the current row after any given column, make a new row, close that one, then resume showing the "data" columns?
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item insertion-point">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
</div>
</div>
<button class="btn btn-primary insert-row">Insert Row</button>
</body>
</html>
CSS:
.item {
border: 1px solid #f00;
}
.pane {
background: #999;
height: 100px;
}
JavaScript:
$('.insert-row').on('click', function() {
code = '</div><!--end row--><div class="row"><div class="col-sm-12 pane"></div></div>';
$('.insertion-point').after(code);
});
EDIT:
The code string above probably should end with <div class="row"> to re-open the row. But I tried that and it still doesn't work.
The problem here is that visually it looks like my solution works. Though in reality, it's creating bad HTML.
Further explanation (I think this is hard to explain). Here is what's happening, and this is NOT what I want:
I need that inserted row to be at the same level as the row it was erroneously inserted into.
Desired HTML after jQuery manipulation
<div class="container">
<div class="row">
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item insertion-point">
Data
</div>
</div>
<div class="row">
<div class="col-sm-12 pane"></div>
</div>
<div class="row">
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
</div>
</div>
Further Ramblings
Maybe, since this is Bootstrap, there's some way I can use the grid system to have the same effect.
The code below should resolve your issue. Check out the code snippet and demo:
$('.insert-row').on('click', function() {
var row = $('<div/>',{class:"row"}),
code = '<!--end row--><div class="row"><div class="col-sm-12 pane">New</div></div>',
rest = $('.insertion-point').nextAll(),
dest = $('.insertion-point').closest('.row');
dest.after( row.append( rest ) ).after( code );
});
<script src="//code.jquery.com/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item insertion-point">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
</div>
</div>
<button class="btn btn-primary insert-row">Insert Row</button>
i worked out this four you: JsFiddle
$(document).ready(function() {
var firstRow = $('.row');
$('.insert-row').on('click', function() {
var code = $('<div/>', {clas: 'row'}).append($('<div/>', {class: "col-sm-12 pane"})),
row = $('<div/>', {class: 'row'}),
items = $('.insertion-point').nextAll();
row.append(items);
firstRow.after(row);
firstRow.after(code);
});
});
Update:
after seen the nextAll function by jQuery .. this will be much faster:
updated fiddle
I think what you need is appendTo which will append html onto the specified tag. In this case you want to append a div onto your row.
http://api.jquery.com/appendto/
Just get rid of the closing tag in the code variable and your code will work and be well formed
code = '</div><!--end row--><div class="row"><div class="col-sm-12 pane"></div></div>';
should be
code = '<div class="row"><div class="col-sm-12 pane"></div></div>';
Also you need to insert rows after / before other rows like so
$('.insert-row').on('click', function() {
code = '<div class="row"><div class="col-sm-12 pane"></div></div>';
$('.insertion-point').closest(".row").after(code);
});
The above code finds where you want to insert (which I changed to be an id selector since you want to insert after one unique element). However you want to find the closest parent element (or this one) that is a row so that you insert a row after that row. This way you can choose a row or a column to insert after and it will always insert a row after the closest row properly.
Lucky for you browsers are very forgiving when it comes to syntax errors in HTML. They will remove the initial closing tag (which is unnecessary) and use the rest of your HTML. But some browser may behave differently and that is what you have to be careful of.
You need to add a new row after the first by removing the elements after the insertion point and including them in the new row.
You can't treat the DOM like a text editor when inserting html.
$('.insert-row').on('click', function() {
var $insertEL=$('.insertion-point');
var code = '<div class="row"><div class="col-sm-12 pane"></div></div>';
/* create new row and append all siblings after insertion point element*/
var $newRow=$(code).append($insertEL.nextAll());
/* add new row to DOM*/
$insertEL.closest('.row').after($newRow);
});
DEMO
Got it!
Layout solved by using Bootstrap grid, very little jQuery DOM manipulation. I don't know why I didn't think of this earlier. Sheesh. I've been coding for hours non-stop, my brain is fried.
Solution: http://jsbin.com/zopiquzore
This is correct, yes?

Categories

Resources