So I wanna print an object to my page and I have no idea how to write the code in JS so that on my page it prints multiple divs for each object.
What I wanna do is insert this
<div class="cv-block">
<div id="parent_div_1">
obiect.firstn
obiect.lastn
</div>
<div id="parent_div_2">
obiect.date
</div>
obiect.message
</div>
into this java script function
function afisare (lista) {
var randuri = "";
lista.forEach(function (obiect) {
randuri += ;
});
$("#obiect").html(randuri);}
Thank you in advance for your time.
best way to do this is using template literal which is supported by ES6.
if you want to use it in older browser you should use babel.
$("#obiect").html(`<div class="cv-block">
<div id="parent_div_1">
${obiect.firstn}
${obiect.lastn}
</div>
<div id="parent_div_2">
${obiect.date}
</div>
${obiect.message}
</div>`)
also there is ES5 code for it.
$("#object").html("<div class=\"cv-block\">\n <div id=\"parent_div_1\">\n obiect.firstn\n obiect.lastn\n </div>\n\n <div id=\"parent_div_2\">\n obiect.date\n </div>\n\n obiect.message\n\n </div>");
Related
currently i'm making a web scraper with node.Js using cheerio. i want to get the data inside the first of class="panel-items-list.
the html look like this
<div class="margin-bottom-=30">
<div class="side-list-panel">
<ul class="panel-item-list">...</ul>
</div>
</div>
<div class="margin-bottom-=30">
<div class="side-list-panel">
<ul class="panel-item-list">...</ul>
</div>
</div>
i already did like this
const relateArticle = $('.panel-items-list').map((i, section)=>{
let articles = $(section).find('h5');
return articles.text();
}).get();
but it return the data from both class="panel-items-list". how do i get data just from one class ? sorry my english is bad. thanks in advance !
To get the first class only from the .panel-item-list use .get(0) that means you are only selecting the first index found using .map
Also, in your current code jQuery your are not selecting the right class selector.
In addition use .trim() method when getting the text to clean up any unseen spaces within the text.
Live Working Demo:
const relateArticle = $('.panel-item-list').map((i, section) => {
let articles = $(section).find('h5');
return articles.text().trim();
}).get(0)
console.log(relateArticle) //Foo
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="margin-bottom-=30">
<div class="side-list-panel">
<ul class="panel-item-list">
<h5>
Foo
</h5>
</ul>
</div>
</div>
<div class="margin-bottom-=30">
<div class="side-list-panel">
<ul class="panel-item-list">
<h5>
Bar
</h5>
</ul>
</div>
</div>
Use first():
$('.panel-items-list').first().find('h5').text()
I'm finishing up a memory game for school and I'd really like the cards to flip with a CSS animation, which on it's own is pretty straight forward. However I'm pretty new to JavaScript and JQuery which is leading to some trouble with achieving the proper container structure I need to make the cards flip when they are clicked.
Presently the game pieces generate within the board as follows:
const generate=(cards)=>{
cards.forEach(function(card, i) {
$(".gameBoard")
.append($("<div>").addClass("front")//
.append($("<div>").addClass("back").append($("
<img>").attr("src", cards[i]))));
});
};
OR:
<div class="gameBoard>
<div class="front"></div>
<div class="back"><img src="cards"></div>
</div>
But in order for the animation to function properly both the front and back divs need to exist in the same container like this:
<div class="gameBoard>
<div class="flip">
<div class="front></div>
<div class="back"><img src="cards></div>
</div>
</div>
How can I add the div I need (.flip) but have it contain the front and back divs, not just append on to the other divs being generated within the .gameboard container.
Thanks.
It's much simpler to create your DOM using template literals rather than jQuery methods. That way you just describe the HTML as you're accustomed to.
const generate=(cards)=>{
cards.forEach(function(card, i) {
$(".gameBoard").append(`
<div class=flip>
<div class=front></div>
<div class=back><img src="${cards[i]}"</div>
</div>
`);
});
};
generate([
"https://dummyimage.com/180x120/f00/fff.png&text=one",
"https://dummyimage.com/180x120/0f0/fff.png&text=two",
"https://dummyimage.com/180x120/00f/fff.png&text=three",
]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class=gameBoard></div>
You'll notice the ${cards[i]}, which lets you perform string interpolation by executing at runtime the code in the braces.
Here's a vanilla JS version.
const generate=(cards)=>{
var gb = document.querySelector(".gameBoard");
cards.forEach(card =>
gb.insertAdjacentHTML("beforeend", `
<div class=flip>
<div class=front></div>
<div class=back><img src="${card}"</div>
</div>
`)
);
};
generate([
"https://dummyimage.com/180x120/f00/fff.png&text=one",
"https://dummyimage.com/180x120/0f0/fff.png&text=two",
"https://dummyimage.com/180x120/00f/fff.png&text=three",
]);
<div class=gameBoard></div>
It also uses card instead of cards[i], and an arrow function for the callback.
And this one performs a single append.
const generate=(cards)=>{
document.querySelector(".gameBoard")
.insertAdjacentHTML("beforeend", cards.map(card =>
` <div class=flip>
<div class=front></div>
<div class=back><img src="${card}"</div>
</div>`).join(""));
};
generate([
"https://dummyimage.com/180x120/f00/fff.png&text=one",
"https://dummyimage.com/180x120/0f0/fff.png&text=two",
"https://dummyimage.com/180x120/00f/fff.png&text=three",
]);
<div class=gameBoard></div>
I am new to Browserify but I think I am missing something. From what I can tell I have to load every single module for my app into bundle.js but I am totally lost as to how to call functions, objects etc for specific pages.
For instance, this is my main.js file:
var bootstrap = require('bootstrap');
var mainUI = require('./main-ui');
var foodGrid = require('./food-grid');
mainUI();
The mainUI(); bit is fine, as I need that to execute on every page to make my sidebar to work.
However, foodGrid is something that I only want to load when I visit the food page. If I do:
var bootstrap = require('bootstrap');
var mainUI = require('./main-ui');
var foodGrid = require('./food-grid');
mainUI();
foodGrid();
Then foodGrid() is called on every page, this is not correct.
foodGrid() is defined as:
module.exports = function () {
console.log('Test');
})
I can not see a way of getting this to work since everything is bundled into bundle.js, without doing some logic around the functions to determine if the user is on a certain page, which seems ridiculous.
My food page is:
#extends('layouts.master')
#section('title')
Enquiries
#stop
#section('body')
<div class="row">
<div class="col-xs-12">
<h3>Food</h3>
</div>
</div>
<div id="food_controls" class="row">
<div class="col-xs-9">
Control
</div>
<div class="col-xs-3">
<div class="input-group">
<span class="input-group-addon"><img width="20" src="{!!asset('images/loader.gif')!!}"><i class="fa fa-search"></i></span>
<input class="form-control" type="text" placeholder="Start typing to search...">
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div id="foodGrid"></div>
</div>
</div>
#stop
#section('js')
{!! HTML::script('js/libs/kendo.all.min.js') !!}
<script>
enquiriesGrid();
</script>
#stop
The above gives me the error that foodGrid() is undefined.
Can someone tell me how to work with this? I must being missing something big.
(I am using Laravel 5, that is what all that blade syntax is)
elixir(function(mix) {
mix.browserify('main.js');
});
I have blocks of HTML & JS and want to compile it all in to one JS file so I can use a one line embed on external client sites. Like <script src="http://example.com/assets/js/myembed.min.js"></script>
Sample Code
<div class="page-container">
<div class="container">
<br />
<button class="btn launchConfirm">Launch Confirm</button>
</div>
</div>
<div id="confirm" class="modal hide fade">
<div class="modal-body">
Do you want to continue?
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-primary" data-value="1">Continue</button>
<button type="button" data-dismiss="modal" class="btn" data-value="0">Cancel</button>
</div>
</div>
<script>
$('.launchConfirm').on('click', function (e) {
$('#confirm')
.modal({ backdrop: 'static', keyboard: false })
.one('click', '[data-value]', function (e) {
if($(this).data('value')) {
alert('confirmed');
} else {
alert('canceled');
}
});
});
</script>
Should I wrap it all in document.write or is the a better method to achieve this? And if this is the best way, what is the best way to do this automatically, I.e. Using Grunt/Gulp?
E.g.
document.write("<div class=\"page-container\">");
document.write(" <div class=\"container\">");
document.write(" <br \/>");
document.write(" <button class=\"btn launchConfirm\">Launch Confirm<\/button>");
document.write(" <\/div>");
document.write("<\/div>");
Thanks in advance.
Do not use document.write.
var x = '<div> All your html code store in variable </div>';
$("#InsertHere").html(x); // insert where you want
or document.getElementById("InsertHere").innerHTML = x;
// continue your actual code once those elements are ready
$('.launchConfirm').on('click', function (e) { }
It is quite not possible to embbed html code without using DOM insertion methods which always requires selector. You could create a unique class name
and the tag that has that class name will be inserting this code. This is what jQuery does too.
<div class=".innerHTML"></div> // you have to ask them to create such element
Quick and dirty would be to copy the HTML to text-editor of choice, replace newlines and indentation, then add all html as one line. And use single quotes so you dont have to escape the double-quotes
i have divs like this:
<div class="oferta SYB">
<div class="infoferta">
<div class="datosoferta">
<div class="ofertapagas">Pagás<br/> $ 67</div>
<div class="ofertavalor">Valor<br /> $ 160</div>
<div class="ofertadescuento">Descuento $ 93</div>
</div>
</div>
i want to order the divs with the class="oferta" by the value in "ofertapagas" or the value in "ofertavalor" or the value in "ofertadescuento", i dont know how to, i cannot use the database, i just can use Jquery, i am using the last version of it.
Some Help please!!
jQuery abstracts Array.prototype.sort. Since jQuery wrappet sets are Array like objects, you can just call .sort() on them or apply sort on them.
var $datosoferta = $('.datosoferta');
$datosoferta.children().detach().sort(function(a,b) {
return +a.textContent.split(/\$/)[1].trim() - +b.textContent.split(/\$/)[1].trim();
}).appendTo($datosoferta);
See http://typeofnan.blogspot.com/2011/02/did-you-know.html
Demo: http://jsfiddle.net/Rfsfs/
Using ui. JQuery UI - Sortable Demos & Documentation
For your code;
$( ".offer" ).sortable({
update: function(event, ui) { // do post server. }
});
If you place those offer DIVs in some sort of container (another DIV?) you can then fetch all the offers and sort by their childrens' values.
In the HTML below, I put the offer divs inside a container div, and added a data-value attribute to each of the child divs containing data, for easier access (no regular expressions required).
<div id="ofertas_container">
<div class="infoferta">
<div class="datosoferta">
<div class="ofertapagas" data-value="67">Pagá $ 67</div>
<div class="ofertavalor" data-value="130">Valor $ 130</div>
<div class="ofertadescuento" data-value="93">Descuento $ 93</div>
</div>
</div>
<div class="infoferta">
<div class="datosoferta">
<div class="ofertapagas" data-value="57">Pagá $ 57</div>
<div class="ofertavalor" data-value="150">Valor $ 150</div>
<div class="ofertadescuento" data-value="43">Descuento $ 43</div>
</div>
</div>
<div class="infoferta">
<div class="datosoferta">
<div class="ofertapagas" data-value="107">Pagá $ 107</div>
<div class="ofertavalor" data-value="250">Valor $ 250</div>
<div class="ofertadescuento" data-value="1000">Descuento $ 1000</div>
</div>
</div>
</div>
Pagá
Valor
Descuento
The JS / jQuery function:
ofertas_sort = function(sort_key) {
// array of offer divs
var ofertas = $('.infoferta');
// the div classname corresponding to the key by which
// we are sorting
var sort_key_sel = 'div.' + sort_key;
// in large lists it'd be more efficient to calculate
// this data pre-sort, but for this instance it's fine
ofertas.sort(function(a, b) {
return parseInt($(sort_key_sel, a).attr('data-value')) -
parseInt($(sort_key_sel, b).attr('data-value'));
});
// re-fill the container with the newly-sorted divs
$('#ofertas_container').empty().append(ofertas);
};
Here's the code on jsFiddle, with some links at the bottom of the HTML to demo the sorting: http://jsfiddle.net/hans/Rfsfs/2/
I changed some of the values to make the sorting more visible.