Loop thru object to output icons javascript - javascript

Sorry for the poor title–I didn't know what to put.
Anyways, I have this object I want to loop thru in order to dynamically output some icons onclick:
<button id="btn">hit me</button>
var socialMedia = {
facebook: "http://facebook.com",
twitter: "http://twitter.com",
instagram: "http://instagram.com",
dribbble: "http://dribbble.com",
social: function() {
var output = "<ul>";
var myList = document.querySelectorAll('.socialSpot');
for (var key in arguments[0]) {
output += '<li><a href="' + this[key] + '"><img src="_assets/'
+ key + '.png" alt="' + key + 'icon"></a></li>';
}
output += '</ul>';
for (var i = myList.length - 1; i >= 0; i--) {
myList[i].innerHTML = output;
};
}
};
var theBtn = document.getElementById('btn');
theBtn.addEventListener('click', function() {
socialMedia.social(socialMedia);
}, false);
I know I could remove the method and instantiate it while passing the object, but I was wondering how I could go about it this way. In other words, I want to leave the function as a method of the socialMedia {}. Any pointers?

Just add a if (typeof obj[key] != "string") continue; test to your loop:
…
social: function(obj) {
var output = "<ul>";
var myList = document.querySelectorAll('.socialSpot');
for (var key in obj) {
if (typeof this[key] != "string") continue;
output += '<li><a href="' + this[key] + '"><img src="_assets/'
+ key + '.png" alt="' + key + 'icon"></a></li>';
}
output += '</ul>';
for (var i = myList.length - 1; i >= 0; i--) {
myList[i].innerHTML = output;
};
}
Of course, simply using another object would be so much cleaner:
var socialMedia = {
data: {
facebook: "http://facebook.com",
twitter: "http://twitter.com",
instagram: "http://instagram.com",
dribbble: "http://dribbble.com"
},
social: function(obj) {
var data = obj || this.data;
var output = "<ul>";
for (var key in data) {
output += '<li><a href="' + data[key] + '"><img src="_assets/'
+ key + '.png" alt="' + key + 'icon"></a></li>';
}
output += '</ul>';
var myList = document.querySelectorAll('.socialSpot');
for (var i = myList.length - 1; i >= 0; i--) {
myList[i].innerHTML = output;
};
}
};
var theBtn = document.getElementById('btn');
theBtn.addEventListener('click', function() {
socialMedia.social();
}, false);

You don't need to pass in socialMedia to have access to the socialMedia object inside of the social function. As the social function's execution context is socialMedia's execution context, this will be bound to socialMedia inside of social. In other words
var socialMedia = {
...
social: function(){
var socialMedia = this;
//socialMedia.facebook == this.facebook
//socialMedia.twitter == this.twitter
//you can loop through this inside of for in to get these properties
//(although you may want to make sure to avoid the function again)
}
};
this will be available no matter what, so you can call socialMedia.social() without any arguments.

You could do it with an easier API and still keep both together (without having them both together)
var socialMedias = (function() {
var medias = {
facebook: "http://facebook.com",
twitter: "http://twitter.com",
instagram: "http://instagram.com",
dribbble: "http://dribbble.com",
};
return function(socials) {
if (!socials) {
return medias;
}
var output = "<ul>";
var myList = document.querySelectorAll('.socialSpot');
for (var key in socials) {
output += '<li><a href="' + this[key] + '"><img src="_assets/'
+ key + '.png" alt="' + key + 'icon"></a></li>';
}
output += '</ul>';
for (var i = myList.length - 1; i >= 0; i--) {
myList[i].innerHTML = output;
};
};
})();
So socialMedias() return the map, individual entry can be fetched like socialMedias().facebook and socialMedias(myArgument) would run the method

Related

Only show objects in array that contain a specific string

I was trying to make something where you can type a string, and the js only shows the objects containing this string. For example, I type Address1 and it searches the address value of each one then shows it (here: it would be Name1). Here is my code https://jsfiddle.net/76e40vqg/11/
HTML
<input>
<div id="output"></div>
JS
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
var restoName = [], restoAddress = [], restoRate = [], restoImage= [];
for(i = 0; i < data.length; i++){
restoName.push(data[i].name);
restoAddress.push(data[i].address);
restoRate.push(data[i].rate);
restoImage.push(data[i].image);
}
for(i = 0; i < restoName.length; i++){
document.getElementById('output').innerHTML += "Image : <a href='" + restoImage[i] + "'><div class='thumb' style='background-image:" + 'url("' + restoImage[i] + '");' + "'></div></a><br>" + "Name : " + restoName[i] + "<br>" + "Address : " + restoAddress[i] + "<br>" + "Rate : " + restoRate[i] + "<br>" + i + "<br><hr>";
}
I really tried many things but nothing is working, this is why I am asking here...
Don't store the details as separate arrays. Instead, use a structure similar to the data object returned.
for(i = 0; i < data.length; i++){
if (data[i].address.indexOf(searchedAddress) !== -1) { // Get searchedAddress from user
document.getElementById("output").innerHTML += data[i].name;
}
}
Edits on your JSFiddle: https://jsfiddle.net/76e40vqg/17/
Cheers!
Here is a working solution :
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
document.getElementById('search').onkeyup = search;
var output = document.getElementById('output');
function search(event) {
var value = event.target.value;
output.innerHTML = '';
data.forEach(function(item) {
var found = false;
Object.keys(item).forEach(function(val) {
if(item[val].indexOf(value) > -1) found = true;
});
if(found) {
// ouput your data
var div = document.createElement('div');
div.innerHTML = item.name
output.appendChild(div);
}
});
return true;
}
<input type="search" id="search" />
<div id="output"></div>

Facebook Graph API get original picture size not working

Need some help to get a normal or larger image from posts using the Facebook Graph API, at the moment it only gives a 130 x 130 px image in the object.
function fbFetch() {
var access_token = "";
var url = "https://graph.facebook.com/?ids=intel&fields=posts.limit(5){message,created_time,picture.type(normal)}&access_token=' + access_token;
$.getJSON(url, function(response) {
var messages = [];
Object.getOwnPropertyNames(response).forEach(function(page, idx, array) {
response[page].posts.data.forEach(function(post, idx, array) {
messages.push(post);
});
});
function compare(a, b) {
if (a.created_time < b.created_time)
return -1;
if (a.created_time > b.created_time)
return 1;
return 0;
}
var html = "<ul>";
$.each(messages.sort(compare), function(i, fb) {
if (typeof fb.picture != "undefined") {
html += "<li>" + fb.message + "</br>" + '<img SRC="' + fb.picture + '">' + "</br>" + fb.created_time + "</li></br>";
} else {
html += "<li>" + fb.message + "</br>" + fb.created_time + "</li></br>";
}
});
html += "</ul>";
$('.facebookfeed').html(html);
});
}
fbFetch();
<div class="facebookfeed"></div>
Fiddle here: http://jsfiddle.net/6fhq3dat/17/
use full_picture instead of picture
var url = "https://graph.facebook.com/?ids=intel&fields=posts.limit(3){message,created_time,full_picture}&access_token=" + access_token;
demo

Pure Js onclick element doesn't work

I'm having trouble when i run this code under greasemonkey the last position working and run function.
var arry = [];
arry = GM_listValues();
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML = document.getElementById('moje_menu').innerHTML + '<p id="' + arry[i] + '">' + arry[i] + '</p>';
document.getElementById(arry[i]).onclick = delete;
}
On 10 position the last working ... WHY ????
When you replace the innerHTML you remove all previous event handlers.
In plain JS you can detect the click in the div but you need to check the event:
function removeP(p) {
console.log(p.id);
}
var arry = ["a","b","c"];
window.onload=function() {
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '">' + arry[i] + '</p>';
}
document.getElementById('moje_menu').onclick=function(e) {
var event = e?e:window.event,tgt = event.target || event.srcElement;
if (tgt.tagName.toLowerCase()=="p") {
console.log(tgt.id);
}
}
}
<div id="moje_menu"></div>
Alternative is inline since you generate the P anyway
var arry = [];
arry = GM_listValues();
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '" onclick="delete(this)">' + arry[i] + '</p>';
}
You can the modify delete (poor name for a function since delete is a built-in method) to handle the passed paragraph
Example:
function removeP(p) {
console.log(p.id);
}
var arry = ["a","b","c"];
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '" onclick="removeP(this)">' + arry[i] + '</p>';
}
<div id="moje_menu"></div>
In jQuery you can easily delegate:
function removeP() {
console.log(this.id);
}
$(function() {
var arry = ["a","b","c"];
var $menu = $('#moje_menu');
for (var i=0; i<arry.length; i++) {
$menu.append($('<p/>',{"id":arry[i], "text":arry[i]}))
}
$menu.on("click","p",removeP);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="moje_menu"></div>
This is my solution i dont like them but works.
var arry = [];
arry = GM_listValues();
for ( var i = 0; i<arry.length; i++) {
// if(arry[i].search('player')==''){
document.getElementById('moje_menu').innerHTML += '<p class="lista_farm" id="'+arry[i]+'">'+arry[i]+'</p>';
//document.getElementById(arry[i]).onclick = usun_farme;
//}
}
var lista_farm = document.getElementsByClassName('lista_farm');
for(var i = 0; i<lista_farm.length; i++){
lista_farm[i].onclick = usun_farme;
}

Uncaught ReferenceError: variable is not defined on onclick function Javascript

Today , i have been read all the topic about this but couldn't come up with a solution that's why i am opening this topic.
This is my function which creates the view and i am trying to have a onclick function which should directs to other javascript function where i change the textbox value.
<script type="text/javascript">
$('#submitbtnamazon')
.click(function(evt) {
var x = document.getElementById("term").value;
if (x == null || x == "" || x == "Enter Search Term") {
alert("Please, Enter The Search Term");
return false;
}
listItems = $('#trackList').find('ul').remove();
var searchTerm = $("#term").val();
var url = "clientid=Shazam&field-keywords="
+ searchTerm
+ "&type=TRACK&pagenumber=1&ie=UTF8";
jsRoutes.controllers.AmazonSearchController.amazonSearch(url)
.ajax({
success : function(xml) {
$('#trackList')
.append('<ul data-role="listview"></ul>');
listItems = $('#trackList').find('ul');
html = ''
tracks = xml.getElementsByTagName("track");
for(var i = 0; i < tracks.length; i++) {
var track = tracks[i];
var titles = track.getElementsByTagName("title");
var artists = track.getElementsByTagName("creator");
var albums = track.getElementsByTagName("album");
var images = track.getElementsByTagName("image");
var metaNodes = track.getElementsByTagName("meta");
//trackId ="not found";
trackIds = [];
for (var x = 0; x < metaNodes.length; x++) {
var name = metaNodes[x]
.getAttribute("rel");
if (name == "http://www.amazon.com/dmusic/ASIN") {
trackId = metaNodes[x].textContent;
trackIds.push(trackId);
}
}
for (var j = 0; j < titles.length; j++) {
var trackId=trackIds[j];
html += '<div class="span3">'
html += '<img src="' + images[j].childNodes[0].nodeValue + '"/>';
html += '<h6><a href="#" onclick="someFunction('
+trackId
+ ')">'
+trackId
+ '</a></h6>';
html += '<p><Strong>From Album:</strong>'
+ albums[j].childNodes[0].nodeValue
+ '</p>';
html += '<p><Strong>Artist Name:</strong>'
+ artists[j].childNodes[0].nodeValue
+ '</p>';
html += '<p><Strong>Title:</strong>'
+ titles[j].childNodes[0].nodeValue
+ '</p>';
/*html += '<p><Strong>Created:</strong>'
+ releaseDate
+ '</p>';*/
html += '</div>'
}
}
//listItems.append( html );
$("#track").html(html);
$("#track").dialog({
height : 'auto',
width : 'auto',
title : "Search Results"
});
// Need to refresh list after AJAX call
$('#trackList ul').listview(
"refresh");
}
});
});
</script>
This is my other function where i change the textbox value. it works actually with other values e.g. when i give hardcoded string value. I can see the value in the console but for some reason it gives me the error like :
here the string starts with B is AsinId where i take from amazon. I am definitely in need of help because i am totally stucked.
Uncaught ReferenceError: B00BMQRILU is not defined 62594001:1 onclick
<script type="text/javascript">
function someFunction(var1) {
tracktextbox = document.getElementsByName("trackId");
for (var i = 0; i < tracktextbox.length; i++) {
tracktextbox[i].value = var1;
}
$('#track').dialog('close');
}
</script>
The problem is '<h6><a href="#" onclick="someFunction('+trackId+ ')">', from the error it is clear that trackId is a string value, so you need to enclose it within "" or ''. So try
'<h6><a href="#" onclick="someFunction(\'' + trackId + '\')">'

Convert a multidimensional javascript array to JSON?

What is the best way of converting a multi-dimensional javascript array to JSON?
Most of the popular JavaScript frameworks have JSON utility functions included. For instance, jQuery has a function that directly calls a url and loads the JSON result as an object : http://docs.jquery.com/Getjson
However, you can get an open-source JSON parser and stringifier from the json website :
https://github.com/douglascrockford/JSON-js
Then, simply include the code and use the JSON.stringify() method on your array.
The "best" way has been provided by the other posters. If you don't need the full encoding features of the referenced libraries, and only need to encode simple arrays, then try this:
<!DOCTYPE html>
<html>
<head>
<title>Simple functions for encoding Javascript arrays into JSON</title>
<script type="text/javascript">
window.onload = function() {
var a = [
[0, 1, '2', 3],
['0', '1', 2],
[],
['mf', 'cb']
],
b = [
0, '1', '2', 3, 'woohoo!'
];
alert(array2dToJson(a, 'a', '\n'));
alert(array1dToJson(b, 'b'));
};
function array2dToJson(a, p, nl) {
var i, j, s = '{"' + p + '":[';
nl = nl || '';
for (i = 0; i < a.length; ++i) {
s += nl + array1dToJson(a[i]);
if (i < a.length - 1) {
s += ',';
}
}
s += nl + ']}';
return s;
}
function array1dToJson(a, p) {
var i, s = '[';
for (i = 0; i < a.length; ++i) {
if (typeof a[i] == 'string') {
s += '"' + a[i] + '"';
}
else { // assume number type
s += a[i];
}
if (i < a.length - 1) {
s += ',';
}
}
s += ']';
if (p) {
return '{"' + p + '":' + s + '}';
}
return s;
}
</script>
</head>
<body>
</body>
</html>
Not sure I fully understand your question, but if you are trying to convert the object into a string of JSON then you probably want to look at the native JSON support in all the new browsers. Here's Resig's post on it. For browsers that don't yet support it try the json2.js library. JSON.stringify(obj) will convert your object to a string of JSON.
This will convert all combinations of arrays within objects and vice versa including function names:
function isArray(a){var g=a.constructor.toString();
if(g.match(/function Array()/)){return true;}else{return false;}
}
function objtostring(o){var a,k,f,freg=[],txt; if(typeof o!='object'){return false;}
if(isArray(o)){a={'t1':'[','t2':']','isarray':true}
}else {a={'t1':'{','t2':'}','isarray':false}}; txt=a.t1;
for(k in o){
if(!a.isarray)txt+="'"+k+"':";
if(typeof o[k]=='string'){txt+="'"+o[k]+"',";
}else if(typeof o[k]=='number'||typeof o[k]=='boolean'){txt+=o[k]+",";
}else if(typeof o[k]=='function'){f=o[k].toString();freg=f.match(/^function\s+(\w+)\s*\(/);
if(freg){txt+=freg[1]+",";}else{txt+=f+",";};
}else if(typeof o[k]=='object'){txt+=objtostring(o[k])+",";
}
}return txt.substr(0,txt.length-1)+a.t2;
}
You could use the encode function of this library.
I've modified a bit the code previously provided... because a JSON has this format: [{"object":{"property_1":"value_1","property_2":"value_2"}}]
So, the code would be...
<!DOCTYPE html>
<html>
<head>
<title>Simple functions for encoding Javascript arrays into JSON</title>
<script type="text/javascript">
window.onload = function(){
var a = [['property_1','value_1'],['property_2', 'value_2']];
alert("Comienzo..., paso ////"+a+"\\\\\\ a formato JSON");
var jsonSerialized = array2dToJson(a, 'object');
alert(jsonSerialized);
};
// Estructura de JSON [{"object":{"property_1":"value_1","property_2":"value_2"}}]
function array2dToJson(a, p, nl) {
var i, j, s = '[{"' + p + '":{';
nl = nl || '';
for (i = 0; i < a.length; ++i) {
s += nl + array1dToJson(a[i]);
if (i < a.length - 1) {
s += ',';
}
}
s += nl + '}}]';
return s;
}
function array1dToJson(a, p) {
var i, s = '';
for (i = 0; i < a.length; ++i) {
if (typeof a[i] == 'string') {
s += '"' + a[i] + '"';
}
else { // assume number type
s += a[i];
}
if (i < a.length - 1) {
s += ':';
}
}
s += '';
if (p) {
return '{"' + p + '":' + s + '}';
}
return s;
}
</script>
</head>
<body>
<h1>Convertir un Array a JSON...</h1>
</body>
</html>
var t = {}
for(var i=0;i<3;i++) {
var _main = {};
var _dis = {}
var _check = {};
_main["title"] = 'test';
_main["category"] = 'testing';
_dis[0] = '';
_dis[1] = '';
_dis[2] = '';
_dis[3] = '';
_check[0] = 'checked';
_check[1] = 'checked';
_check[2] = 'checked';
_check[3] = 'checked';
_main['values'] = _check;
_main['disabled'] = _dis;
t[i] = _main;
}
alert(JSON.stringify(t));
Try this
use this code and very simple develop for more two array
function getJSON(arrayID,arrayText) {
var JSON = "[";
//should arrayID length equal arrayText lenght and both against null
if (arrayID != null && arrayText != null && arrayID.length == arrayText.length) {
for (var i = 0; i < arrayID.length; i++) {
JSON += "{";
JSON += "text:'" + arrayText[i] + "',";
JSON += "id:'" + arrayID[i] + "'";
JSON += "},";
}
}
JSON += "]"
JSON = Function("return " + JSON + " ;");
return JSON();
}
and 3 array
function getJSON(arrayID, arrayText, arrayNumber) {
var JSON = "[";
if (arrayID != null && arrayText != null && arrayNumber!=null && Math.min(arrayNumber.length,arrayID.length)==arrayText.length) {
for (var i = 0; i < arrayID.length; i++) {
JSON += "{";
JSON += "text:'" + arrayText[i] + "',";
JSON += "id:'" + arrayID[i] + "',";
JSON += "number:'" + arrayNumber[i] + "'";
JSON += "},";
}
}
JSON += "]"
JSON = Function("return " + JSON + " ;");
return JSON();
}
JavaScript will correctly encode an object:
var a = new Object;
var a = {};
JavaScript will not encode an array:
var a = new Array();
var a = [];

Categories