How to load data from two separate XML files? - javascript

I'm trying to load XML data from two separate files. On page load, I want to show data of one file by default. There would be a button on the page to display data from next file.
After load XML files, I need to combine all popup boxes with looping. But my code does not support to loop that popups. how can I implement the below code? Please help.
Here is my code.
$(document).ready(function(){
$.ajax({
type:"GET",
url:"contact.xml",
dataType:"xml",
success:xmlParser2
});
});
function xmlParser2(xml){
var items = $(xml).children().children();
items.sort(function() { return 0.5 - Math.random() });
xml = $(xml).children();
let i = 0;
let total = $(xml).children().length;
items.each(function (idx,index,item) {
let expireArray = $(this).attr('expires').split('/');
const expireDate = `${expireArray[2]}${expireArray[1]}${expireArray[0]}`;
const now = new Date(),
nowDate = `${now.getFullYear()}${(now.getMonth()+1) <10 ? '0'+(now.getMonth()+1): (now.getMonth()+1)}${now.getDate()}`;
if (nowDate > expireDate) {
return;
}
let tag = $(this).prop("tagName")+index;
let nextIdx = idx + 1;
let prevIdx = idx - 1;
//to make cyclic
nextIdx = nextIdx == total ? 0 : nextIdx;
prevIdx = prevIdx == -1 ? (total -1) : prevIdx;
let image = '<img style="background-image:url(' + $(this).find("image").text() + ')"' + '" />';
let image2 = '<div><img src="' + $(this).find("image").text() + '" width="100%" alt="' + '" />' + '</div>';
let head = '<div>' + $(this).find("head").text() + '</div>';
let html = `<div class="col-sm-4 random" id="random">
<div class="thumbnail randomdiv3" id="border" >
<a href="#${tag + idx}" id="openModalBtn">
<div>${image}</div>
<h5>${head}</h5>
</a>
</div>
</div>`;
let popup = `<div id="${tag + idx}" class="overlay">
<div class="popup">
‹
›
<h6>${head}</h6>
<a class="close" href="#">×</a>
<div>${image2}</div>
</div>
</div>`;
i++;
if(i <= 3) {
$("#xmldata").append(html);
$("#image_boxes").append(html);
}
else{
$("#rest_image_boxes").append(html);
}
$("#popup").append(popup);
});
var hash = window.location.hash;
if(hash != ""){
$("a[href='"+hash+"']").find("h5").click();
}
$("a[id='openModalBtn']").click(function(){
window.location.hash = $(this).attr("href");
});
}
function xmlParser3(xml){
var items = $(xml).children().children();
items.sort(function() { return 0.5 - Math.random() });
xml = $(xml).children();
let i = 0;
let total = $(xml).children().length;
items.each(function (idx,index,item) {
let expireArray = $(this).attr('expires').split('/');
const expireDate = `${expireArray[2]}${expireArray[1]}${expireArray[0]}`;
const now = new Date(),
nowDate = `${now.getFullYear()}${(now.getMonth()+1) <10 ? '0'+(now.getMonth()+1): (now.getMonth()+1)}${now.getDate()}`;
if (nowDate > expireDate) {
return;
}
let tag = $(this).prop("tagName")+index;
let nextIdx = idx + 1;
let prevIdx = idx - 1;
//to make cyclic
nextIdx = nextIdx == total ? 0 : nextIdx;
prevIdx = prevIdx == -1 ? (total -1) : prevIdx;
let image = '<img style="background-image:url(' + $(this).find("image").text() + ')"' + '" />';
let image2 = '<div><img src="' + $(this).find("image").text() + '" width="100%" alt="' + '" />' + '</div>';
let head = '<div>' + $(this).find("head").text() + '</div>';
let html = `<div class="col-sm-4 random" id="random">
<div class="thumbnail randomdiv3" id="border" >
<a href="#${tag + idx}" id="openModalBtn">
<div>${image}</div>
<h5>${head}</h5>
</a>
</div>
</div>`;
let popup = `<div id="${tag + idx}" class="overlay">
<div class="popup">
‹
›
<h6>${head}</h6>
<a class="close" href="#">×</a>
<div>${image2}</div>
</div>
</div>`;
$("#rest_image_boxes").append(html);
$("#popup").append(popup);
});
var hash = window.location.hash;
if(hash != ""){
$("a[href='"+hash+"']").find("h5").click();
}
$("a[id='openModalBtn']").click(function(){
window.location.hash = $(this).attr("href");
});
}
$('#myButton1').click(function(e){
e.preventDefault();
$.ajax({
type:"GET",
url:"data.xml",
dataType:"xml",
success:xmlParser3
});
});
<div class="row" id="xmldata"></div>
<section>
<div class="container">
<input type="button" value="View All" id="myButton1" class="reveal" style="float: right;" onclick="toggler('toggle_container');">
<div id="toggle_container" class='hide'>
<div class="block">
<div class="row" id="rest_image_boxes"></div>
</div>
</div>
</div>
</section>
<section id="popup"></section>
Plunker

Related

I cannot add the class "unread" to the append content of a certain data-id

I want to add the "unread" class to an append content with a specific data-id. The following line of code works fine in the browser console. However, when the code is run it does not add the class "unread".
var idMessage = message[message.length-1].id;
$('#visitors').find('h5[data-id=' + idMessage + ']').addClass('unread');
The goal is to add "unread" in the following line of code:
$("#visitors").append('<h5 class="' + state + '" data-id=' + visitors[i].idSession + '>' + visitors[i].visitorOnline + '</h5>');
I will provide you with a code snippet
<div id="conexion-chat">
<button id="btn-conexion-chat" onclick="initWebSocket();">Iniciar chat</button>
</div>
<div id="display-chat" style="display: none;">
<div id="visitors"></div>
<br />
<textarea id="chatRoomField" rows="10" cols="30" readonly></textarea> <br/>
<input id="sendField" value="" type="text">
<button id="sendButton" onclick="send_message();">Enviar</button>
</div>
function initWebSocket(){
$('#conexion-chat').css('display', 'none');
$('#display-chat').css('display', '');
websocket = new WebSocket("ws://localhost:8080/o/echo");
websocket.onopen = function (event) {
websocket.send(json_user());
};
websocket.onclose = function(event) {
localStorage.clear();
console.log("DESCONECTADO");
};
websocket.onmessage = function(event) {
var message = event.data;
processMessage(message);
};
websocket.onerror = function(event) {
console.log("ERROR: " + event.data);
};
}
function visitorSelected(event){
var visitorSelected = $(event.target).data('id');
localStorage.setItem('visitorSelected', visitorSelected);
websocket.send(json_messages(visitorSelected, '${email}', '${read}'));
document.getElementById("chatRoomField").innerHTML = "";
}
function processMessage(message){
if(message == '${disconnected}'){
document.getElementById("chatRoomField").innerHTML += "El patrocinador no se encuentra conectado." + "\n";
}else {
var json_message = JSON.parse(message);
var visitorSelected = localStorage.getItem('visitorSelected');
if(json_message.hasOwnProperty('message') && message.length > 0){
var message = json_message.message;
var text = "";
if('${currentUserRol}' != '${rolPreferences}'){
for(var i=0; i<message.length; i++){
text += message[i].from + ": " + message[i].message + "\n";
document.getElementById("chatRoomField").innerHTML = text;
}
}else{
if(message[message.length-1].id == visitorSelected || message[message.length-1].idTo == visitorSelected){
for(var i=0; i<message.length; i++){
text += message[i].from + ": " + message[i].message + "\n";
document.getElementById("chatRoomField").innerHTML = text;
}
}else{
var idMessage = message[message.length-1].id;
$('#visitors').find('h5[data-id=' + idMessage + ']').addClass('unread');
}
}
}
if(json_message.hasOwnProperty('visitors') && json_message.visitors.length > 0){
var visitors = json_message.visitors;
var state;
$("#visitors h5").remove();
for (var i = 0; i < visitors.length; i++) {
state = (visitors[i].idSession == visitorSelected)? "selected" : "not-selected";
$("#visitors").append('<h5 class="' + state + '" data-id=' + visitors[i].idSession + '>' + visitors[i].visitorOnline + '</h5>');
}
if(visitorSelected == null){
$("#visitors h5:first-child").attr("class", "selected");
visitorSelected = $("#visitors h5:first-child").attr("data-id");
localStorage.setItem('visitorSelected', visitorSelected);
}
}
}
}
$('#visitors').on('click', 'h5.not-selected', visitorSelected);
*Note: The entire code has not been submitted, but a code snippet.
Thanks!
Regards!

Default tab active not working in jquery and javascript

I have a table to show with tabs on it. i have implemented it.
But having issue in when I reload the page of this table view, i need to make the tab 1 as active as defult. I have added the code, but it is not working
below is the page code
function showDataInTable(data) {
var wrapper = $("<div></div>");
var wrapperUL = $("<ul class='nav nav-tabs'></ul>");
var tabContentDiv = $("<div class='tab-content'></div>");
var tab;
for (var i = 0; i < data.length; i++ ) {
tab = data[i];
wrapperUL.append('<li role="sheet_name" class="tab-li' + i + '"><a href="#' + i +
'" aria-controls="' + i + '" role="tab" data-toggle="tab">' + tab.sheetName +
'</a></li>');
var div = $('<div role="tabpanel" class="tab-pane" id="' + i + '" sheet_name="' + tab.sheetName + '"></div>');
var table = $('<table class="table table-condensed table-bordered table-hover"><thead><tr><th>#</th><th>Name</th><th class="danger" style="width:20%">Requirements</th><th class="success">Services</th><th>Location</th><th>Dimension</th></tr></thead><tbody></tbody></table>'); // create html tags as jQuery objects, not very long strings with data
var rowCount = 0;
for (var j = 0; j < tab.tabContent.length; j++) {
var obj = tab.tabContent[j];
// div += '<div sheet_name="' + obj.sheet_name + '">' + obj.name + '</div>';
var row = $('<tr><td></td><td></td><td class="danger" style="width:20%"></td><td class="success"></td><td></td><td></td></tr>');
rowCount++;
row.find("td").eq(0).text(rowCount);
row.find("td").eq(1).text(obj.name);
row.find("td").eq(2).text(obj.requirements ? obj.requirements[0].requirement : '');
row.find("td").eq(3).text(obj.services ? obj.services[0].service : '');
row.find("td").eq(4).text(obj.location ? obj.location : '');
row.find("td").eq(5).text(obj.dimensions ? obj.dimensions : '');
table.find("tbody").append(row);
if (obj.requirements || obj.services) {
var nMax = obj.services.length > obj.requirements.length ? obj.services.length : obj.requirements.length;
if (nMax > 1) {
var nRows = [];
for (var conut = 1; conut < nMax; conut++) {
nRows[conut] = $('<tr><td></td><td></td><td class="danger" style="width:20%"></td><td class="success"></td><td></td><td></td></tr>');
if (obj.requirements.length > conut) {
nRows[conut].find("td").eq(2).text(obj.requirements[conut].requirement);
}
if (obj.services.length > conut) {
nRows[conut].find("td").eq(3).text(obj.services[conut].service);
}
}
table.find("tbody").append(nRows);
}
}
}
div.append(table);
tabContentDiv.append(div);
}
$('.nav-tabs li').eq(0).addClass('active');
$('.tab-content div').eq(0).addClass('active');
wrapper.append(wrapperUL);
wrapper.append("<p> </p>");
wrapper.append(tabContentDiv);
return wrapper;
}

Create second or next <li> under default <li> after reload page | jQuery, LocalStorage

I try to create LocalStorage data for My Folder Creation .
HTML :
This is my default li. I call it All audience folder's
<!-- Result goes here -->
<ul class="nav">
<li>
<div class="zf-folder" style="width: 232px;">
<div class="_tabFolder _itemPosition" style="height: 50px;border-bottom:1px groove; user-select: none;">
<div class="_sideFolder"></div>
<div class="_iconText" style="width: 215px">
<div class="ellipsis">
<div class="_1i5w">
<div class="_icon-col">
</div>
</div>
All Audiences<span class="hyperspan" style="position:absolute; width:100%; height:100%; left:0; top:0;"></span>
</div>
</div>
</div>
</div>
</li>
</ul>
jQuery :
var count = 1;
$(".submitButton").click(function() {
let label = count++;
// make a function that returns the DOM with updated count
function getNewList(foldername) {
var addFolder = '<li>' +
'<div class="zf-folder" style="width: 232px;">' +
'<div class="_tabFolder _itemPosition" style="height: 50px;border-bottom:1px groove; user-select: none;">' +
'<div class="_sideFolder"></div>' +
'<div class="_iconText" style="width: 215px">' +
'<div class="ellipsis">' +
'<div class="_iconFolder">' +
'<div class="_icon-col">' +
'</div>' +
'</div>' +
'<a href="#folder' + label +
'" data-toggle="tab" style="text-decoration: none;">' +
foldername + '<span class="hyperspan" style="width:100%; height:100%; left:0; top:0;"></span></a>' +
'</div>' +
'</div>' +
'</div>' +
'</div>' +
'</li>';
return addFolder;
}
var inputan = $("#input_nameFolder").val();
// update the result array
var result = JSON.parse(localStorage.getItem("folderList"));
if (result == null) {
result = [];
}
let newfolderHTML = getNewList(inputan);
result.push({
folder: newfolderHTML
});
// save the new result array
localStorage.setItem("folderList", JSON.stringify(result));
// append the new li
$(".nav").append(newfolderHTML); // i want include myDiv
//clear input
$("#input_nameFolder").val('');
});
// on init fill the ul
var result = JSON.parse(localStorage.getItem("folderList"));
if (result != null) {
//get the nav reference in DOM
let nav = $(".nav");
//clear the html contents
nav.html('');
for (var i = 0; i < result.length; i++) {
var item = result[i];
$(".nav").append(item.folder);
}
}
How to adding new <li> tag under my default li (all audience)
after reload page/click run jsfiddle when user input a new value?
You can see after adding an input and reload web / jsfiddle, new input folder's (second li) overwrite all audience (first li).
JSFiddle
you just have to save the initial element upon initialization, see:
// on init fill the ul
var result = JSON.parse(localStorage.getItem("folderList"));
if (result != null) {
//get the nav reference in DOM
let nav = $(".nav");
//clear the html contents
nav.html('');
for (var i = 0; i < result.length; i++) {
var item = result[i];
$(".nav").append(item.folder);
}
} else {
//Save the "All Audiences" content upon empty folderList
let initialElement = [];
initialElement.push({
folder: $('ul.nav').html()
});
localStorage.setItem("folderList", JSON.stringify(initialElement));
}
See: JSFiddle

I have this code that works in JSFiddle but not on my site

I want to create a new button every time the post button is clicked and each new button should have its own counter. This works in JSFiddle but not when I use it.
$(function() {
$('.input_button').on('click', function() {
text = $('.input_text').val();
var btn = $("<button></button>");
btn.text("Like!");
$("body").append(btn);
btn.after("<span class='clicks'></span>")
var clicks = 0;
btn.click(function() {
clicks++;
$(this).next(".clicks").html(clicks);
});
if (text != undefined) {
post = '<div class="post test--post">' + '<img src="photo.JPG" width="20" height="25" alt=""/>' + '<p><span>jaleelg: </span></p>' + text +
'<p>Clicks: <a id="clicks">0</a></p>' + "<br>" + Date() + " " + '</div>';
new_post = $('.post_feed').append($(post))
new_post = $('.post_feed').append($(btn))
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<h3 id="feed">My Posts</h3>
<section class="post_feed test--post_feed">
</section>
</section>
<input class="input_text test--input_text" type="text">
<button type="submit" class="input_button test--input_button">Post</button>
<div id="clicks">
</div>
You have to change in this:
btn.click(function() {
clicks++;
$(this).next(".clicks").html(clicks);
});
Like this:
btn.click(function() {
$('.clicks').html(function(i, val) { return val*1+1 });
});
This pen works:
http://codepen.io/anon/pen/ygRxOq?editors=0010
$(function() {
$("body").on("click",".like",function(e) {
clicks = $(e.target.parentElement).find("#clicks").text() / 1 + 1;
$(e.target.parentElement).find("#clicks").text(clicks);
});
$('.input_button').on('click', function() {
text = $('.input_text').val();
post = '<div class="post test--post">' +
'<img src="photo.JPG" width="20" height="25" alt=""/>' +
'<p><span>jaleelg: </span></p>' + text +
'<p>Clicks: <a id="clicks">0</a></p>' +
'<br>' + Date() + '<br>'+
'<button class="like">Like!</button>'+
'</div>';
new_post = $('.post_feed').append($(post));
});
});

Increment javascript variable function onclick

This the page I'm working on:
http://gacc.nifc.gov/gbcc/predictive/PSA_ERCmap/Dev/PSAERCmap1.html
When you click on a shaded area the chart associated with the area pops up. What I'm trying to figure out is how to get the "Next PSA" link at the bottom to advance the chart in the popup to the next PSA every time you click it. I've figured out how to get it to advance by one PSA, but can't get it past that one. You'll see if you click on the link.
I have a function (called replace) that replaces the image source for the chart with a link to the next PSA number up. However, I can't figure out how to get it to increment. I tried PSA++ and PSA=PSA1 but neither of them work.
Here's my code:
<title>DEV PSA ERC Map DEV</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function overlay(a) {
PSA = a.id;
var numeric = a.id.replace('GB', '');
PSAnum = Number(numeric)
PSA1 = PSAnum + 1;
nextPSA = ('0' + PSA1).slice(-2);
var overlayContent = '';
overlayContent += '<div id="overlay">';
overlayContent += '<div>';
var imgsrce = '';
imgsrce += 'Charts/WebCharts/GB';
imgsrce += numeric;
imgsrce += '/ERCGraph.PNG';
overlayContent += '<img id="chartimage" src="';
overlayContent += imgsrce;
overlayContent += '" />';
overlayContent += '<br /><b><h1> Close</b></h1>';
overlayContent += '<b><h1> Next PSA</b></h1>';
overlayContent += '</div>';
overlayContent += '</div>';
$("#overlay").replaceWith(overlayContent);
el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
if (el.style.visibility == "visible") {
//el.style.visibility="hidden";
}
} //end of overlay function
function replace(a) {
image = document.getElementById('chartimage');
console.log(image.src);
console.log(PSA);
image.src = 'Charts/WebCharts/GB';
image.src += nextPSA;
image.src += '/ERCGraph.PNG';
PSA++;
console.log(PSA);
} //end of replace function
$('.overlay-bg').click(function() {
closePopup();
});
function closePopup() {
el = document.getElementById("overlay");
el.style.visibility = "hidden";
}
$(function() {
$.get("getDate.php", function(data) {
document.getElementById("timestamp").innerHTML = "<b>RAWS observations updated on " + data + "</b>";
});
});
var file;
file = 'GB_PSAdata_Real.js';
$.getJSON(file, function(events) {
var gbname = Object.keys(events);
var divContent = '';
divContent += '<div id="map">';
divContent += '<map name="mapmap">';
for (i = 0; i < gbname.length; i++) {
var PSA = (gbname[i]);
JSONcoords = events[PSA][0].Coords;
JSONcoordString = JSONcoords.toString();
divContent += '<area id="' + PSA + '" href="#" shape="poly" coords="';
divContent += JSONcoordString;
divContent += '" onclick="overlay(this)">';
// console.log(divContent)
}
divContent += '</map>';
divContent += '<img src="GetPSAavg.php" width="826" height="1005" usemap="#mapmap" />';
divContent += '</div>';
$("#map").replaceWith(divContent);
//$("#overlay").replaceWith(overlayContent);
;
})
</script>
</head>
<div id="overlay">
</div>
<body>
<div id="header">
<img src="PSlogo.png" style="height:75px">
<img src="GBlogo.png" style="height:75px">
<span><b>Great Basin ERC Percentiles</b> *Experimental*</span>
</div>
<div id="main">
<div id="map"></div>
<div id="timestamp">RAWS Observations Updated</div>
<div id="legend">
<img src="LegendFull2.png" id="legendIMG">
</div>
</div>
</body>
</html>
You need to move the code that increments the number into the replace() function, so it gets executed each time replace() is called. Currently it is executed only once when the overlay() function is called.
First, explicitly declare a global variable (outside of any function):
var currentPSANum = null;
Place this line inside the overlay() function:
currentPSANum = Number(a.id.replace('GB',''));
Then use the following for the replace() function:
function replace(a) {
currentPSANum++;
var image = document.getElementById('chartimage');
image.src = 'Charts/WebCharts/GB' + ('0' + currentPSANum).slice(-2) + '/ERCGraph.PNG';
}

Categories

Resources