I don't understand why it is important to view or see when its just the logic I'm looking for.. However I just added the index.html file that can make things show... I hope it helps anyone !
what I'm trying to achieve is..
var small = document.getElementsByClassName("small");
var story = document.getElementsByClassName("story");
small.onclick = function() { story.style.display = "block"; }
I'm aware they should be done for loop and added as [i] in the end of both vars...
But how can i relate each small to story when they're both same id...
How can I tell
document.getElementsByClassName("small")[0];
to show
document.getElementsByClassName("story")[0];
when I have Multiple Class Values...
Thought about adding (this) in onclick() html tag but im not experienced enough....
Here's the Main Code:
var div = document.getElementById("content");
var ajax = new XMLHttpRequest();
ajax.open('GET', 'rss.json', true);
ajax.onreadystatechange = function()
{
if(ajax.readyState == 4 && ajax.status == 200)
{
var items = JSON.parse(ajax.responseText);
var output = '<ul class="main">';
for(var key in items)
{
output += '<li class="IDZ"><b><pre>' + items[key].IDZ + '</b></pre></li>';
output += '<li class="topic"><h1><u>' + items[key].topic + '</u></h1></li>';
output += '<li id="" class="small"><a href="#" >' + items[key].small + '</a></li><br>';
output += '<li class="story">' + items[key].story + '</li><br>';
output += '<li class="media"><img src='+items[key].media+'>' + '</li>';
output += '<hr>';
}
output += '</ul>';
div.innerHTML = output;
}
}
ajax.send(null);
rss.json file
{
"rss1":
{
"IDZ" : 1,
"topic" : "Topic One",
"small" : "A Brief Intro about this story.",
"story" : "Main Story starts when A B C were born to become all good and tidy for the little things that made IDZ : 1 A Story",
"media" : "images/IDZ1.jpg"
},
"rss2":
{
"IDZ" : 2,
"topic" : "Topic 2",
"small" : "A Brief Intro about another story.",
"story" : "Main Story starts when A B C were born to become all good and tidy for the little things that made IDZ : 2 A Story",
"media" : "images/IDZ2.jpg"
}
}
<!DOCTYPE html>
<html encoding="utf-8" >
<head>
<title>json parser</title>
<style>
/* { border: 0; margin:0; padding: 0;} */
body { position: relative; }
ul { }
li { list-style-type: none; font-size:1em;}
a { text-decoration: none; }
a:visited { color: #f22; }
.id { text-align: center; }
</style>
<script>
document.onreadystatechange = function()
{
if(document.readyState == "complete")
{
var loadscript = document.getElementById("content");
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "script.js";
loadscript.appendChild(script);
}
}
</script>
</head>
<body>
<div id="content">
</div>
</body>
</html>
You could use the "data" attribute to store the key and also include the key in the id as follows:
for(var key in items)
{
output += '<li id="" data-key="'+ key +'" class="small"><a href="#" >' + items[key].small + '</a></li><br>';
output += '<li class="story" id="story_key_'+ key +'">' + items[key].story + '</li><br>';
}
small.onclick = function(elem)
{
story.style.display = "block";
var storyKey = elem.dataset.key;
var storyItem = document.getElementById("story_key_" + storyKey);
}
(Note: this is only an idea, this code isn't working code)
Related
I am trying to write some JavaScript code to load JSON from a URL and then display it in a linked listview that navigates to a new panel within the webapp that I am creating. I have successfully rendered the listview from the JSON data however, I cannot seem to get a new panel open. Any ideas? My code so far it below -
<li class="divider">Brown Eyes</li>
<div id="output1"></div>
<li class="divider">Green Eyes</li>
<div id="output2"></div>
<script>
var myContainer = "";
var panel_view = "";
var a = new XMLHttpRequest();
a.open("GET", "https://api.myjson.com/bins/1dwnm", true);
a.onreadystatechange = function () {
console.log(a);
if (a.readyState == 4) {
var obj = JSON.parse(a.responseText);
for (i = 0; i < obj.length; i++) {
if (obj[i].eyeColor == 'brown') {
var myContainer = '<ul class="list"><li><a href="#item_profiles'+i+'" class="icon pin">' + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + '</li></ul>';
document.getElementById('output1').innerHTML += myContainer;
}
if (obj[i].eyeColor == 'green') {
var myContainer = '<ul class="list"><li><a href="#item_profiles'+i+'" class="icon pin">' + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + '</li></ul>';
document.getElementById('output2').innerHTML += myContainer;
}
}
}
}
a.send();
panel_view += '<div class="panel" data-title="'+obj[i].name.first+'" id="item_profiles'+i+'" data-footer="none"><img src="http://localhost:3000/uploads/'+obj[i].name.first+'" style="width:100%;height:auto;"><p style="padding-left: 10px; padding-right: 10px;">'+obj[i].name.first+'</p></div>';
$('#profiles_panel').after(panel_view);
</script>
EDITED -
So, the purpose of this is to achieve the below code to use just Native JavaScript as oppose to jQuery. Here is the jQuery version of the code -
<script type="text/javascript">
$(document).ready(function () {
var panel_view_admissions = "";
$.getJSON( 'http://localhost:3000/admissions', function(data) {
$.each( data, function(i, name) {
$('ul.list-admissions').append('<li>'+name.title+'</li>');
panel_view_admissions += '<div class="panel" data-title="'+name.title+'" id="item_admissions'+i+'" data-footer="none"><img src="http://localhost:3000/uploads/'+name.image+'" style="width:100%;height:auto;"><p style="padding-left: 10px; padding-right: 10px;">'+name.content+'</p></div>';
});
$('#admissions_panel').after(panel_view_admissions);
});
});
</script>
What i have:
JSON with id, name, position, department and address.
That same JSON have over 1000 random employees looped to a table.
Every person have a custom attribute (user_id) and same css class for hovering.
One hidden prepared and styled div for information when is hovered on one employee.
What i need:
I need when i hover on some employee to display all that employee information like name, position, department and address. Keep in mind that hover is working, but informations are still static. So basically, my logic is when custom attr user_id and JSON id match = fill the html.
How can i do that?
var xmlhttp = new XMLHttpRequest();
var url = "https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/189576/1743369/lDhMee0RoA1IO5D/generated.json";
var employees;
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
employees = JSON.parse(this.responseText);
write(employees);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function write(arr) {
var i;
var out = '<table>';
for(i = 0; i < arr.length; i++) {
out += '<tr>';
out += '<td class="hoverKartX" user_id="' + arr[i].id + '">' + arr[i].name + '</td>';
out += '<td>' + arr[i].position + '</td>';
out += '</tr>';
}
out += '</table>';
document.getElementById('employees').innerHTML = out;
}
$(function() {
var moveLeft = 20;
var moveDown = 10;
$('.hoverKartX').hover(function(e) {
//$(this).parent().find(".hoverKart").show();
$(".hoverKart").show();
}, function() {
$('.hoverKart').hide();
});
$('.hoverKartX').mousemove(function(e) {
$(".hoverKart").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
// preventing 'falling' to the right on smaller screen
if ($(".hoverKart").position()['left'] + $('.hoverKart').width() > $(window).width()) {
$(".hoverKart").css("left", $(window).width() - $(".hoverKart").width());
};
// preventing 'falling from the bottom of the page'
if ((e.pageY + moveDown + $(".hoverKart").height()) > ($(window).scrollTop() + $(window).height())) {
$(".hoverKart").css("top", $(window).height() - $(".hoverKart").height() + $(window).scrollTop());
}
});
});
.hoverKart {
position: absolute;
width: 400px;
height: 220px;
border-radius: 25px;
border: 1px solid #999;
z-index: 1;
display: none;
background: #fff;
}
<!-- hidden div-->
<div class="hoverKart">
<div class="container">
<div class="cardTop"><p><!-- JSON DATA (ID) --></p></div>
<div class="imgHolder">
<img class="employee" src="img/img.jpg" alt="employee image">
<img class="eLogo" src="img/logo.jpg" alt="logo">
</div>
<div class="eInformation">
<p class="eName"><!-- JSON DATA (NAME) --></p>
<p class="ePos"><!-- JSON DATA (DEPARTMENT) --></p>
<div class="eDep">
<img src="img/icons-dep/5.png" alt="department logo">
</div>
<p class="eOp">Operations</p>
<p class="eOp2"><!-- JSON DATA (ADDRESS) --></p>
</div>
</div>
</div>
<div id="employees"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have update your code and created a fiddle:
Check the working Fiddle.
$(function(){
var xmlhttp = new XMLHttpRequest();
var myGlobalJson;
var url = "https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/189576/1743369/lDhMee0RoA1IO5D/generated.json";
var employees;
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
employees = JSON.parse(this.responseText);
myGlobalJson = employees;
write(employees);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function write(arr) {
var i;
var out = '<table>';
for(i = 0; i < arr.length; i++) {
out += '<tr>';
out += '<td class="hoverKartX" user_id="' + arr[i].id + '">' + arr[i].name + '</td>';
out += '<td>' + arr[i].position + '</td>';
out += '</tr>';
}
out += '</table>';
document.getElementById('employees').innerHTML = out;
bindMethods();
}
//$(function() {
function bindMethods(){
var moveLeft = 20;
var moveDown = 10;
$('.hoverKartX').hover(function(e) {
//$(this).parent().find(".hoverKart").show();
var currentUserId = parseInt(($(this).attr('user_id')));
//console.log(myGlobalJson);
//console.log(typeof parseInt($(this).attr('user_id')));
$.each(myGlobalJson, function(i, item) {
//console.log($(this).attr('user_id'));
if(item.id === currentUserId){
$(".hoverKart .cardTop").html(item.id);
$(".hoverKart .eName").html(item.name);
$(".hoverKart .ePos").html(item.position);
$(".hoverKart .eOp2").html(item.address);
return false;
}
});
$(".hoverKart").show();
}, function() {
$('.hoverKart').hide();
});
$('.hoverKartX').mousemove(function(e) {
$(".hoverKart").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
// preventing 'falling' to the right on smaller screen
if ($(".hoverKart").position()['left'] + $('.hoverKart').width() > $(window).width()) {
$(".hoverKart").css("left", $(window).width() - $(".hoverKart").width());
};
// preventing 'falling from the bottom of the page'
if ((e.pageY + moveDown + $(".hoverKart").height()) > ($(window).scrollTop() + $(window).height())) {
$(".hoverKart").css("top", $(window).height() - $(".hoverKart").height() + $(window).scrollTop());
}
});
}
//});
});
There were some issues in existing code:
You should bind hover method to field only when your write method execution is finished. Otherwise, it's working will be inconsistent, depending on how fast table is created.
I hope, It will solve your purpose.
Alright apology for different answer as it's whole different way to fix this issue like below,
As your main problem is your "hoverKartX" jquery events are not binded to any elements because your html elements are generated dynamically from xmlhttp, so first you need to make sure your events are binded to your html elements after generating it, probably you need to refactor your code and move your $('.hoverKartX').hover()... and $('.hoverKartX').mousemove()... in your function write(arr) as you had attached your mousehover and mousemove event's code in global context which will bind to no html element at the time of page load because you are generating these elements dynamically using xmlhttp,
then access your custom html attribute user_id by using jquery's attr like $(this).attr('user_id') in your mousehover or mousemove event and do whatever you want to do...
I am using the code below which i found on: http://www.rahulsingla.com/blog/2011/08/itunes-performing-itunes-store-search-in-javascript to pull songs from Itunes based on a keyword, however i only want to pull songs on page-load without having to use the search box, lets say my keyword is "search-keyword", i would like to display songs immidiately on page-load or refresh without using the search box, here is the code below:
<html>
<head>
<title>iTunes - Music Search in javascript</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<style type="text/css">
.songs-search-result {
border: 1px solid Gray;
margin-bottom: 5px;
padding: 5px;
}
.songs-search-result .label{
display: inline-block;
width: 200px;
}
</style>
<script type="text/javascript">
function urlEncode(obj) {
var s = '';
for (var key in obj) {
s += encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]) + '&';
}
if (s.length > 0) {
s = s.substr(0, s.length - 1);
}
return (s);
}
function performSearch() {
var params = {
term: encodeURIComponent(jQuery('#search-keyword').val()),
country: 'US',
media: 'music',
entity: 'musicTrack',
//attribute: 'artistTerm,albumTerm,songTerm,musicTrackTerm',
limit: 20,
callback: 'handleTunesSearchResults'
};
var params = urlEncode(params);
var url = 'http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsSearch?' + params;
var html = '<script src="' + url + '"><\/script>';
jQuery('head').append(html);
}
function handleTunesSearchResults(arg) {
var results = arg.results;
var html = '';
for (var i = 0; i < results.length; i++) {
var item = results[i];
var obj = {
source: 0,
track_id: item.trackId,
track_name: item.trackCensoredName,
track_url: item.trackViewUrl,
artist_name: item.artistName,
artist_url: item.artistViewUrl,
collection_name: item.collectionCensoredName,
collection_url: item.collectionViewUrl,
genre: item.primaryGenreName
};
results[i] = obj;
html += '<div class="songs-search-result">';
html += '<span class="label">Track:</span>{0} '.replace("{0}", obj.track_name);
html += 'Preview '.replace("{0}", item.previewUrl);
html += 'Full Song '.replace("{0}", obj.track_url);
html += '<span class="label">Track Price:</span>{0} {1}<br />'.replace("{0}", item.trackPrice).replace("{1}", item.currency);
html += '<span class="label">Artist:</span>{1}<br />'.replace("{0}", obj.artist_url).replace("{1}", obj.artist_name);
html += '<span class="label">Collection:</span>{1}<br />'.replace("{0}", obj.collection_url).replace("{1}", obj.collection_name);
html += '<span class="label">Collection Price:</span>{0} {1}<br />'.replace("{0}", item.collectionPrice).replace("{1}", item.currency);
html += '<span class="label">Primary Genre:</span>{0}<br />'.replace("{0}", obj.genre);
html += '</div>';
}
jQuery('#itunes-results').html(html);
}
</script>
</head>
<body>
Please enter a search term below (e.g. Michael):<br />
<input type="text" id="search-keyword" title="Enter Search Keyword" />
<br />
<input type="button" value="Perform iTunes Search" onclick="performSearch();" />
<div id="itunes-results">
</div>
</body>
</html>
I am trying to create a pinterest like webpage using mansory.js and I am having trouble appending the unique description to each image. I know that the last line of my code is wrong but I have no idea how to fix it. I am basically adding all of the description tags into one span for each image.
I've tried looking at several other stackoverflow questions such as jQuery: Add element after another element and add image/s inside a div with jquery
but with no luck.
My entire pen is here http://codepen.io/OG/pen/VLEXgz
HTML
<body>
<h1>Camper Stories</h1>
<div id="content"></div>
</body>
CSS
h1{
text-align:center;
font-family: 'Lobster', cursive; font-size:80px;
color:purple;
}
#content {
width: auto;
margin: 0 auto;
}
.item {
display: inline-block;
float: left;
width: 300px;
height:300px;
margin: 2em;
position:relative;
}
.item img {
width: 300px;
height: auto;
}
JS
var url = 'http://www.freecodecamp.com/stories/hotStories';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var i;
var headlines = [];
//loop through json get need attributes
//for(i = 0; i < arr.length; i++){
for (i = 0; i < 5; i++) {
var headline = arr[i].headline;
headlines.push(headline);
var authorImg = arr[i].author.picture;
//console.log(img);
//error function
//if there is no thumbnail link the get author image
if (img === "") {
$('#content').append('<div class="item">' + '' + '<img id="myImg" src="' + authorImg + '" alt="' + headline + '" />' + '' + '</div>');
} else {
//if there is a thumbnail image then use that image
$('#content').append('<div class="item" id="hi">' + '' + '<img id="myImg" src="' + img + '" alt="' + headline + '" />' + '' + '</div>');
//if there is a 404 error with loading the thumbnail image then use author's image
$('img').one('error', function () {
this.src = '' + authorImg;
})
}
$(arr[i].headline).insertAfter("img");
}
}
See http://codepen.io/anon/pen/YXJvEK Is that what you mean? Append the headline after the corresponding image only?
$("<span>" + arr[i].headline+"</span>").insertAfter($("img").eq(i));
You should build your elements like this:
var wrapper = $("<div />");
var link = $("<href />");
var img = $("<img />");
...
Then add attributes and classes needed and append them to each other.
link.append(img);
wrapper.append(link);
...
In that way your code gets much more maintainable and you can append your span easily to your img (don't know exactly where you want the description).
Edit, since I've got my hands on a pc, here's the code you could use.
function myFunc (data) {
if(typeof data === "undefined") return; // output some error
for (var i = 0; i < data.length; i++) {
var item = data[i];
var upVote = item.rank;
var href = item.link;
var image = (item.image === "") ? item.author.picture : item.image;
var headline = item.headline;
// build elements
var wrapper = $("<div />");
var link = $("<a />");
var img = $("<img />");
var description = $("<span />");
// add attributes and classes
wrapper.addClass("item");
link.attr("href", link);
// you can also set multiple attributes at once
img.attr({"src": image, "alt": headline});
description.text(headline); // text(string) adds string to element
// append elements onto each other
link.append(img);
wrapper.append(link, description);
$("div.content").append(wrapper); // attach elements to DOM
}
}
I'm having trouble narrowing this one down.
In IE8 and above works fine.
I don't even know how to debug this, since IE7 doesn't have developer tools.
The error says line 6256 (first in the snippet bellow); char 6 (letter 'i' of 'if'); code 0:
if ( typeof elem.getElementsByTagName !== "undefined" ) { /***this is the line that throws Invalid Argument***/
// handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration
jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );
// Splice the scripts into ret after their former ancestor and advance our index beyond them
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
i += jsTags.length;
}
The code is part of function clean.
Any ideas on how to tackle this?
EDIT I:
When I open debugger in IE9, put breakpoint on that line and then open stack trace this is what I see:
So I assume that it's triggered by $(document).ready
EDIT II
It seems that jsfiddle is currently down so I'm posting the code here and creating jsbin snippet:
http://jsbin.com/avajuw/1/edit
HTML:
<div id="navigation-block" style="width: 154px; height: 100%;">
<ul id="sliding-navigation">
<li class="sliding-element">
<h4>Docs</h4>
</li>
</ul>
</div>
JS:
$(document).ready(function () {
// the actual code I run is in comments
// var baseRestUrl = top.location.protocol + '//' + top.location.host + top.location.pathname + 'jaxrs';
var baseRestUrl = 'http//host:port/archive/jaxrs';
var linksRestUrl = baseRestUrl + '/links';
var fileRestUrl = baseRestUrl + '/file';
// var params = top.location.search;
var params = 'pnd=231352122&pgv=654321321321';
// $.getJSON(linksUrl, function(json) { //to get something like:
var json = {
"links": {
"lista": [{
"clipExt": "pnd",
"docId": "1203200110003774",
"imageDesc": "Front b/w",
"imageName": "Img_f_bw"
}, {
"clipExt": "pgv",
"docId": "1203200110003774",
"imageDesc": "Front gray",
"imageName": "Img_f_gr"
}]
}
};
//var lista = (!json.links.lista[1]) ? json.links : json.links.lista;
//alert(lista);
$.each(json.links.lista, function(i, item) {
var clipExt = item.clipExt;
var fileLink = fileRestUrl + '?' +
'un=' + item.docId + '&' +
'ext=' + clipExt + '&' + clipExt + '=' + extractParam(params, clipExt);
$('#sliding-navigation').append(
"<li class=\"sliding-element\">" + item.imageDesc + "</li>");
});
});
function extractParam(url, paramName) {
var tmp = (url.match(RegExp("[?|&]" + paramName + '=(.+?)(&|$)')) || [null])[1];
return tmp;
}
the given "error" is missleading :) sometimes if you give some "not existing elements" to jquery, where it hopes to have some element, it just does nonsense ... please try to locate the problem somewhere in your written code: do you have any function calls that you registered for (document).ready() ? Is every dom-node a real dom-node and not null/undefined?
This html works in IE9 when IE7 mode is turned ON, while your example at jafiddle breaks in the same mode. It's same code you posted, but put in the local file. So problem must be elsewhere.
Create html file with this markup (same as your example) and open in your IE7. Does it work?
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<div id="navigation-block" style="width: 154px; height: 100%;">
<ul id="sliding-navigation">
<li class="sliding-element">
<h4>Dokumenti</h4>
</li>
</ul>
</div>
<script>
$(document).ready(function () {
// the actual code I run is in comments
// var baseRestUrl = top.location.protocol + '//' + top.location.host + top.location.pathname + 'jaxrs';
var baseRestUrl = 'http//host:port/archive/jaxrs';
var linksRestUrl = baseRestUrl + '/links';
var fileRestUrl = baseRestUrl + '/file';
// var params = top.location.search;
var params = 'pnd=231352122&pgv=654321321321';
// $.getJSON(linksUrl, function(json) { //to get something like:
var json = {
"links": {
"lista": [{
"clipExt": "pnd",
"docId": "1203200110003774",
"imageDesc": "Front b/w",
"imageName": "Img_f_bw"
}, {
"clipExt": "pgv",
"docId": "1203200110003774",
"imageDesc": "Front gray",
"imageName": "Img_f_gr"
}]
}
};
//var lista = (!json.links.lista[1]) ? json.links : json.links.lista;
//alert(lista);
$.each(json.links.lista, function(i, item) {
var clipExt = item.clipExt;
var fileLink = fileRestUrl + '?' +
'un=' + item.docId + '&' +
'ext=' + clipExt + '&' + clipExt + '=' + extractParam(params, clipExt);
$('#sliding-navigation').append(
"<li class=\"sliding-element\">" + item.imageDesc + "</li>");
});
});
function extractParam(url, paramName) {
var tmp = (url.match(RegExp("[?|&]" + paramName + '=(.+?)(&|$)')) || [null])[1];
return tmp;
}
</script>
</body>
</html>