retrieve data from json file to create slider - javascript

I have JSON file which code shown below. I try to retrieve it's data to create slider elements.
Here is the JSON object.
{
"slider":[{
"img" : "images/1.jpg",
"title" : "Beady little eyes",
"expert" : "Little birds pitch by my doorstep"
},
{
"img" : "images/2.jpg",
"title" : "Beady little eyes",
"expert" : "Little birds pitch by my doorstep"
},
{
"img" : "images/3.jpg",
"title" : "Beady little eyes",
"expert" : "Little birds pitch by my doorstep"
},
{
"img" : "images/4.jpg",
"title" : "Beady little eyes",
"expert" : "Little birds pitch by my doorstep"
}
]}
and I use below jquery code to retrieve data from JSON and generate html.
$.getJSON('data.json', function(data){
$('.slider').append('<ul/>');
$.each(data, function(key, val){
for(var i = 0; i < val.length; i++ ){
var mhtml = '<li><div class="bannerImg"><img src="'+val[i].img+'" /></div>';
mhtml += '<h1 class="title">'+val[i].title+'</h1>';
mhtml += '<p class="expert">'+val[i].expert+'</p>';
mhtml += '</li>';
$('.slider ul').append( $(mhtml) );
}
});
});
is there any better way to do this. Because still it's not have preloader.

try something like this
$(function(){
var json = {
"slider":[{
"img" : "images/1.jpg",
"title" : "Beady little eyes",
"expert" : "Little birds pitch by my doorstep"
},
{
"img" : "images/2.jpg",
"title" : "Beady little eyes",
"expert" : "Little birds pitch by my doorstep"
},
{
"img" : "images/3.jpg",
"title" : "Beady little eyes",
"expert" : "Little birds pitch by my doorstep"
},
{
"img" : "images/4.jpg",
"title" : "Beady little eyes",
"expert" : "Little birds pitch by my doorstep"
}]};
// if you are getting json like above response in ajax
// then simply retrive slider and iterate over it
var mhtml = '';
$.each(json.slider, function(key, val){
mhtml += '<li><div class="bannerImg"><img src="'+val.img+'" /></div>';
mhtml += '<h1 class="title">'+val.title+'</h1>';
mhtml += '<p class="expert">'+val.expert+'</p>';
mhtml += '</li>';
});
var $ul = $('<ul>').append($(mhtml));// append DOM only one time.
$('.slider').append($ul);
})
Alternative
var mhtml = '<ul>';
$.each(json.slider, function(key, val){
mhtml += '<li><div class="bannerImg"><img src="'+val.img+'" /></div>';
mhtml += '<h1 class="title">'+val.title+'</h1>';
mhtml += '<p class="expert">'+val.expert+'</p>';
mhtml += '</li>';
});
mhtml += '</ul>';
$('.slider').append($(mhtml));// append DOM only one time.

Related

jquery+on iterating loop how can i know which element is clicked

I am having a list which is nothing but country flag, country name and country code which actually i derived from JSON
and i had written for loop to render the html elements like this
data =
[
{
"name": "INDIA ",
"code": "93",
"url": 'https://www.countryflags.io/in/flat/64.png'
}, {
"name": "JAPAN ",
"code": "355",
"url": 'https://www.countryflags.io/jp/flat/64.png'
}]
for (var i = 0; i < data.length; i++) {
var countryName = data[i].name;
var countrtDialCode = data[i].code;
var countryUrl = data[i].url;
var badge = document.createElement('div');
badge.className = 'badge';
badge.innerHTML =
'<div id="listSection">'+
'<div style="display:flex">'+
'<div id="flagSection">'+'<img style="height:10px;width:20px;margin-top:4px;" src='+countryUrl+'>'+'</div>'+' '+
'<div id="nameSection">' + countryName + '</div>' +' '+
'<div id="codeSection">' + countrtDialCode + '</div>'
+'</div>'+
'</div>'
document.getElementById('countries-list').appendChild(badge);
}
also i have a divs section
<div id="inputSection"> </div>
<div id="countries-list">
</div>
and i have done like when you click on input section the list will come and i can choose from the list and i need ONLY the flag should be shown
<script type="text/javascript">
$(document).ready(function(){
$('#countries-list').addClass('hideSection').removeClass('showSection')
});
$('#inputSection').click(function(){
$('#countries-list').addClass('showSection').removeClass('hideSection')
})
</script>
so when i click india JSON from list , i should display indian flag in inputSection again if i click input section list should come and again if i choose NEPAL, indian flag should be replaced with NEPAL flag.
Have 2 problem.First one i am unable to write click function in INNERHTML to identify which country clicked and second how to retrieve the flag section and show it in inputSection.
Any fiddle will be highly helpful and thankful
If all you need is a clone of the flag section in the input section, then this is all you need:
$('.listSection').on('click', function() {
$('#inputSection').html( $('.flagSection', this).clone() );
});
However, you have to convert every occurrence of id in the HTML in your JS to class, as in the working demo below. Id attribute values should be unique.
$(function() {
const data = [{
"name": "INDIA ",
"code": "93",
"url": 'https://www.countryflags.io/in/flat/64.png'
}, {
"name": "JAPAN ",
"code": "355",
"url": 'https://www.countryflags.io/jp/flat/64.png'
}];
for (var i = 0; i < data.length; i++) {
var countryName = data[i].name;
var countrtDialCode = data[i].code;
var countryUrl = data[i].url;
var badge = document.createElement('div');
badge.className = 'badge';
badge.innerHTML =
'<div class="listSection">'+
'<div style="display:flex">'+
'<div class="flagSection">'+'<img style="height:10px;width:20px;margin-top:4px;" src='+countryUrl+'>'+'</div>'+' '+
'<div class="nameSection">' + countryName + '</div>' +' '+
'<div class="codeSection">' + countrtDialCode + '</div>'
+'</div>'+
'</div>'
document.getElementById('countries-list').appendChild(badge);
}
$('.listSection').on('click', function() {
console.log( {name: $('.nameSection',this).text(), code: $('.codeSection', this).text()} );
$('#inputSection').html( $('.flagSection', this).clone() );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="inputSection"> </div>
<div id="countries-list">
</div>
NOTE
Since there's not mention in the documentation of .html( jQueryObject ) even thought it works in the above demo, I'll provide an alternative that uses .empty() and .append() methods:
$('#inputSection').empty().append( $('.flagSection', this).clone() );

Using object attribute as image source

I'm trying to pass the video object's image attribute as the source so I can display the image on the screen when the program runs. For obvious reasons, it can't find the source, because no file has the name 'videoObj1.image'. I was wondering if there is a workaround, maybe to take the text of the attribute and pass that as a source? Or even a way to directly use videoObj1.image. Thanks in advance.
Part of Question2.html where I try to use the image attribute as the source:
function displayVideo(videoObj){
var html = "<h1>Search Result " + "</h1>" + "<b>";
html += "Search keyword: " + videoObj.result.searchKeyword;
html += "<table>";
for(var i=0; i < videoObj.result.video.length; i++){
var videoObj1 = videoObj.result.video[i];
html += "<tr>";
html += "<td>" + "<img src=videoObj1.image>" + "</td>";
html += "<td align='right'>" + videoObj1.channel + "</td>";
html += "<td style='color:green' align='right'>";
html += videoObj1.view;
html += "<img src='stockUp.png' />";
html += "</td>";
html += "<td align='right'>" + videoObj1.link + "%</td>";
html += "</tr>";
}
html += "</table>";
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = html;
}
Question2.json:
{
"result": {
"searchKeyword": "Mathematics",
"video": [
{
"title": "Chaos Game",
"channel": "Numberphile",
"view": "428K",
"link": "http://www.youtube.com/watch?v=kbKtFN71Lfs",
"image": "http://i.ytimg.com/vi/kbKtFN71Lfs/0.jpg",
"length": "8:38"
},
{
"title": "Australian Story: Meet Eddie Woo, the maths teacher you wish you'd
had in high school",
"channel": "ABC News (Australia)",
"view": "223K",
"link": "http://www.youtube.com/watch?v=SjIHB8WzJek",
"image": "http://i.ytimg.com/vi/SjIHB8WzJek/0.jpg",
"length": "28:08"
},
{
"title": "Ham Sandwich Problem",
"channel": "Numberphile",
"view": "557K",
"link": "http://www.youtube.com/watch?v=YCXmUi56rao",
"image": "http://i.ytimg.com/vi/YCXmUi56rao/0.jpg",
"length": "5:53"
},
{
"title": "Magic Square Party Trick",
"channel": "Numberphile",
"view": "312K",
"link": "http://www.youtube.com/watch?v=aQxCnmhqZko",
"image": "http://i.ytimg.com/vi/aQxCnmhqZko/0.jpg",
"length": "3:57"
},
{
"title": "The 8 Queen Problem",
"channel": "Numberphile",
"view": "909K",
"link": "http://www.youtube.com/watch?v=jPcBU0Z2Hj8",
"image": "http://i.ytimg.com/vi/jPcBU0Z2Hj8/0.jpg",
"length": "7:03"
}
]
}
}
The problem is you're passing the string "videoObj1.image" to the img src attribute, which obviously is not going to work.
Rather you should pass the variable either by using classic string concatenation approach like this:
"<td><img src=" + videoObj1.image + "></td>";
OR
Using the recommended and modern template literals approach like this:
`<td><img src=${videoObj1.image}></td>`;

display images from json object array

i'm trying to output a series of images in html from an external json file. Unfortunately i cannot change the way the json is formatted and i can't seem to find the right way to access the image urls to use them as src attribute.
this is the code i came up with
$.getJSON( "json/data.json", function( data ) {
var mhtml = '';
$.each(data["item"].images, function(key, val){
for (var i=0; i< data["item"].images.length; i++) {
var img = data["item"]images[i];
}
var alt = data["item"].name;
mhtml += '<li><div class=""><img src="'+val.img+'" /></div>';
mhtml += '<h1 class="title">'+alt+'</h1>';
mhtml += '</li>';
});
var $ul = $('<ul>').append($(mhtml));.
$('#mydiv').append($ul);
});
it successfully counts the images and outputs elements but i can't access the url parameters.
this is how the json file is formatted
{
"item": {
"name": "blue dress",
"details": "graphic print, Logo.",
"composition": "Composition: 94% Cotton, 6% Elastam.",
"modelDetails": [
"Modeal wearing a size M",
"Measures: 86 - 60 - 90",
"Height: 178cm"
],
"images": [
"http://cdn.myoutfits.biz/41/xxxxxxx_001.jpg",
"http://cdn.myoutfits.biz/41/xxxxxxx_002.jpg",
"http://cdn.myoutfits.biz/41/xxxxxxx_003.jpg",
"http://cdn.myoutfits.biz/41/xxxxxxx_004.jpg"
]
}
}
thanks everyone for helping
You have several issues.
looping over the images twice - $.each is a loop
getting the alt each time.
val.img does not exist
Here is a working version - do make sure it is run after mydiv exists
data = {
"item": {
"name": "blue dress",
"details": "graphic print, Logo.",
"composition": "Composition: 94% Cotton, 6% Elastam.",
"modelDetails": [
"Modeal wearing a size M",
"Measures: 86 - 60 - 90",
"Height: 178cm"],
"images": [
"http://cdn.myoutfits.biz/41/xxxxxxx_001.jpg",
"http://cdn.myoutfits.biz/41/xxxxxxx_002.jpg",
"http://cdn.myoutfits.biz/41/xxxxxxx_003.jpg",
"http://cdn.myoutfits.biz/41/xxxxxxx_004.jpg"]
}
}
var alt = data["item"].name,mhtml="";
$.each(data["item"].images, function (i, img) {
mhtml += '<li><div class=""><img src="' + img + '" /></div>';
mhtml += '<h1 class="title">' + alt + '</h1>';
mhtml += '</li>';
});
var $ul = $('<ul>').append($(mhtml));
$('#mydiv').append($ul);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mydiv"></div>
Check if this can help you
var data = {
"item": {
"name": "blue dress",
"details": "graphic print, Logo.",
"composition": "Composition: 94% Cotton, 6% Elastam.",
"modelDetails": [
"Modeal wearing a size M",
"Measures: 86 - 60 - 90",
"Height: 178cm"
],
"images": [
"http://cdn.myoutfits.biz/41/xxxxxxx_001.jpg",
"http://cdn.myoutfits.biz/41/xxxxxxx_002.jpg",
"http://cdn.myoutfits.biz/41/xxxxxxx_003.jpg",
"http://cdn.myoutfits.biz/41/xxxxxxx_004.jpg"
]
}
}
$(document).ready(function(){
console.log(data.item.images);
var alt = data.item.name;
var mhtml="";
$.each(data.item.images,function(k,v){
mhtml += '<li><div class=""><img src="'+data.item.images[k]+'" /></div>';
mhtml += '<h1 class="title">'+alt+'</h1>';
mhtml += '</li>';
})
alert(mhtml)
console.log(mhtml)
$('#mydiv').append(mhtml);
});
http://plnkr.co/edit/kz2WI6FEk0atgoUFJ0Jf?p=preview
you do a foreach and a for ... i don't understand why you do the internal cicle (the for).
If you change
mhtml += '<li><div class=""><img src="'+val.img+'" /></div>';
into
mhtml += '<li><div class=""><img src="'+val+'" /></div>';
you can see some image

How to make: enable / disable option for javascript function with php?

I am still new in php, javascript so I hope that you can help me. :)
I have a LightBox which works good. But Now I want to make enable / disable option for Lightbox in my Wordpress theme.
I have this code for settings options page:
array (
'id' => 'enable_lightbox',
'type' => 'switch',
'title' => __('Enable Lightbox', 'framework'),
'desc' => __('Enable or disable lightbox', 'framework'),
'default' => 1,
),
and this is code for lightbox:
/LightBox
function buildShareThis(url){
var switchTo5x=true;
stLight.options({publisher: "496075ad-6369-474b-ba12-283ff1fe76ac", doNotHash: false, doNotCopy: false, hashAddressBar: false});
var customShareThis = "<div class='share'>";
customShareThis += "<span class='st_sharethis_large' displayText='ShareThis' st_url='"+url+"'></span> ";
customShareThis += "<span class='st_facebook_large' displayText='Facebook' st_url='"+url+"'></span>";
customShareThis += "<span class='st_googleplus_large' displayText='Google +' st_url='"+url+"'></span>";
customShareThis += "<span class='st_twitter_large' displayText='Tweet' st_url='"+url+"'></span> ";
customShareThis += "<span class='st_pinterest_large' st_url='"+url+"'></span>";
customShareThis += "<span class='st_linkedin_large' displayText='LinkedIn' st_url='"+url+"'></span>";
customShareThis += "<span class='st_baidu_large' displayText='Baidu' st_url='"+url+"'></span>";
customShareThis += "<span class='st_reddit_large' displayText='Reddit' st_url='"+url+"'></span>";
customShareThis += "<span class='st_tumblr_large' displayText='Tumblr' st_url='"+url+"'></span>";
customShareThis += "<span class='st_email_large' displayText='Email' st_url='"+url+"'></span>";
customShareThis += "<span class='st_print_large' displayText='Print' st_url='"+url+"'></span>";
customShareThis += "</div>";
return customShareThis;
}
jQuery(".fancybox, a[href$='.jpg'], a[href$='.png'], a[href$='.jpeg'], a[href$='.gif'], .video")
.attr('rel', 'gallery')
.fancybox({
closeClick : false,
nextEffect: 'fade',
prevEffect: 'fade',
beforeShow: function() {
var caption = jQuery(this.element).data("caption") ? jQuery(this.element).data("caption") : "";
this.title = this.title ? this.title + buildShareThis(this.href) + caption : buildShareThis(this.href) + caption;
},
afterShow: function(){
stButtons.locateElements();
},
helpers : {
title : {
type: 'inside'
}
}
});
What code do I need to use to get this working ?
So that I could from settings options page turn on or turn off Lightbox ?
Thank you
php code
if($setting -> default == 1) // Is enable
{
echo '<script>var enable_Light = false; </script>';
}
in LightBox code add a if sectment.
if(enable_Light == true){
jQuery(".fancybox, a[href$='.jpg'], a[href$='.png'], a[href$='.jpeg'], a[href$='.gif'], .video")
.attr('rel', 'gallery')
.fancybox({
closeClick : false,
nextEffect: 'fade',
prevEffect: 'fade',
beforeShow: function() {
var caption = jQuery(this.element).data("caption") ? jQuery(this.element).data("caption") : "";
this.title = this.title ? this.title + buildShareThis(this.href) + caption : buildShareThis(this.href) + caption;
},
afterShow: function(){
stButtons.locateElements();
},
helpers : {
title : {
type: 'inside'
}
}
});
}

JavaScript: Building a HTML table from a nested JSON

I have a problem building a HTML table from the following JSON
[
{
"size" : 167,
"price" : 453400,
"type" : "Neubau",
"children" : false
},
{
"size" : 167,
"price" : 453400,
"type" : "Neubau",
"children" : false
},
{
"size" : 167,
"price" : 453400,
"type" : "Neubau",
"children":[
{
"size" : 167,
"price" : 453400,
"type" : "Neubau",
"children" : false
},
{
"size" : 167,
"price" : 453400,
"type" : "Neubau",
"children" : false
}
]
},
{
"size" : 167,
"price" : 453400,
"type" : "Neubau",
"children" : false
}
]
when fed into these functions
function getRowHTML(dataObject, type) {
cycles = dataObject.length;
var markup = '';
for (var i=0; i < cycles; i++) {
// different markup for each line
switch (type) {
case 'size':
markup += ' <td>' + dataObject[i].size + '</td>';
break;
case 'price':
markup += ' <td>' + addDots(dataObject[i].price) + '€ </td>';
break;
case 'type':
markup += ' <td>' + dataObject[i].type + '</td>';
break;
}
// Check if an object has children and insert children HTML as well
if (dataObject[i].children) {
markup += getRowHTML(dataObject[i].children,type);
}
}
return markup;
}
function getHTML(data) {
var markup = '<table>';
markup += '<tr class="odd">' + getRowHTML(data,'size') + '</tr>';
markup += '<tr class="even">' + getRowHTML(data,'price') + '</tr>';
markup += '<tr class="odd">' + getRowHTML(data,'type') + '</tr>';
markup += '</table>';
return markup;
}
Everything works fine until I add the check for children and the corresponding recursive function call.
Then the result are the first two objects and the children but the last one won't be in the table. Any ideas?
You have forgotten the var on the cycles variable, making it an accidental global. The inner call to getRowHTML overwrites the value of the global cycles in the outer call, making the outer loop end early.
Note you also have HTML-injection problems if any of the properties can contain HTML-special characters. You should HTML-escape any content being inserted into an HTML string. Or, to avoid having to think about that, use DOM methods to create the table instead. eg.
function fillRow(row, items, property) {
for (var i= 0, n= items.length; i<n; i++) {
var item= items[i];
var s= item[property];
if (property==='price')
s= addDots(s)+'\u20Ac'; // €
row.insertCell(-1).appendChild(document.createTextNode(s));
if (item.children)
fillRow(row, item.children, property);
}
}
function makeTable(data) {
var table= document.createElement('table');
var properties= ['size', 'price', 'type'];
for (var i= 0, n= properties.length; i<n; i++) {
var row= table.insertRow(-1);
row.className= i%2===0? 'odd' : 'even';
fillRow(row, data, properties[i]);
}
return table;
}

Categories

Resources