How to add next previous buttons to popup? - javascript

I need to load XML data to next and previous buttons on the popup box. When button click, my code is fail to load the XML data. How can I implement the code.
Here is the script
function xmlParser(xml){
xml = $(xml).children();
$(xml).children().each(function () {
let tag = $(this).prop("tagName");
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">
<a href="#${tag}" id="openModalBtn">
<div>${image}</div>
<h5>${head}</h5>
</a>
</div>`;
let popup = `<div id="${tag}" class="overlay">
<div class="popup">
‹
›
<h6>${head}</h6>
<a class="close" href="#">×</a>
<div>${image2}</div>
</div>
</div>`;
$("#xmldata").append(html);
$("#popup").append(popup);
});
}
Plunker

Firstly div id is being duplicated if you use directly tag name. So use index in for loop and do some simple calculation to get prev & next items, something like:
$(xml).children().each(function (idx) {
let tag = $(this).prop("tagName");
let nextIdx = idx + 1;
let prevIdx = idx - 1;
//to make cyclic rotation
nextIdx = nextIdx == total ? 0 : nextIdx;
prevIdx = prevIdx == -1 ? (total -1) : prevIdx;
//..........check plunker code
http://next.plnkr.co/edit/Sj188FthvFu6H5uv?open=lib%2Fscript.js

Related

Cannot read property : style of Null

I am working on a Trello Board using Vanilla Javascript and I am receiving an error on making my Cards . I have used Local and Session Storage to store the cards and lists respectively but I can't figure out why this error persists after I click on the Add Card Board Button
function newTask(x){
card_index= parseInt(localStorage.getItem("card_indices")) ;
//card_index = parseInt(sessionStorage.getItem("card_indices"));
list_index = parseInt(sessionStorage.getItem("index"));
document.getElementById('myTasks').innerHTML +=
'<div id = "list_' + list_index + ' " class="list-item animated zoomIn" > <h2 id = "title_' + list_index +'" onClick = "modifyObj.titleEdit('+ list_index +')" class="list-item__h2">'+x+'</h2><span id = "span_del_' + list_index + '" class ="btn title-delete" onClick ="modifyObj.titleDelete(' + list_index + ')">\u00D7</span><hr>'+
'<input id = "card_del_' + card_index + '" type="text" class="myInput" placeholder="Title...">' +
'<div class="btn add-items " id = "div_add_list_" onClick = "myCard.titleForm(' + list_index + ',' + card_index + ')" >Add List Item</div>'
'</div>'
sessionStorage.setItem("index", parseInt(sessionStorage.getItem("index"))+1);
}
var myCard = {
card:function(index, card_index){
var enteredElement = document.getElementById('card_del_' + card_index).value;
var textNode = document.getElementsByClassName('text_' + card_index);
textNode.innerText = enteredElement;
if (enteredElement === ""){
alert("You must write something ");
}
else{
document.getElementById("text_").style.display = "block";
}
},
titleForm: function(index,card_index){
element = document.getElementById('card_del_' + card_index);
text = '<li style="display:none" class="text_'+ card_index +'"> <span class = "btn items" onClick = "myCard.cardClose()">u00D7</span></li>'
element.insertAdjacentHTML('beforeend', text);
myCard.card(index,card_index);
localStorage.setItem("card_indices", parseInt(localStorage.getItem("card_indices"))+1);
// card_index+=1;
}};

Ajax function is not display xml data on some mobile browsers

I tried to view XML data in html. This project works fine on desktop browsers but does not work on some mobile browsers. I feel like the issue is obviously but I don't know what to do. Please help.
<div class="row" id="xmldata"></div>
$(document).ready(function() {
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: xmlParser2
});
});
function xmlParser2(xml) {
xml = $(xml).children();
let total = $(xml).children().length;
$(xml).children().each(function(idx, index, item) {
let tag = $(this).prop("tagName");
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 reveal" id="random">
<div class="thumbnail randomdiv3">
<a href="#${tag + idx}" id="openModalBtn">
<div>${image}</div>
<h5>${head}</h5>
</a>
</div>
</div>`;
$("#xmldata").append(html);
});
}

Passing recevied data to Express code with JavaScript

I am using node.js and express.I would like pass received data from socket.io inside div tag. According to received data from socket.io, I want to check with the for and if statements like below.
- for(var i in rows)
-if (rows[i]['senderID'] == "1" && rows[i]['receiverID'] == "2")
div.direct-chat-msg
div.direct-chat-name.pull-left
div.direct-chat-info.clearfix
span.direct-chat-name.pull-left #{rows[i]['senderID']}
span.direct-chat-timestamp.pull-right #{rows[i]['sentDate']}
img.direct-chat-img(src="/images/users/avatar04.png", alt="alt")
div.direct-chat-text #{rows[i]['message']}
-else if (rows[i]['senderID'] == "2" && rows[i]['receiverID'] == "1")
div.direct-chat-msg.right
div.direct-chat-name.pull-right
div.direct-chat-info.clearfix
span.direct-chat-name.pull-left #{rows[i]['senderID']}
span.direct-chat-timestamp.pull-right #{rows[i]['sentDate']}
img.direct-chat-img(src="/images/users/avatar.png", alt="alt")
div.direct-chat-text #{rows[i]['message']}
-else
div.direct-chat-msg.right
p No message!
div.box-footer
div.input-group
input.form-control(type="text" id="message" placeholder="Write a message...")
span.input-group-btn
button.btn.btn-danger.btn-flat(type="submit" onclick="sendMessageJS()") Send
How can i run this code to under the following HTML tag:
div.direct-chat-messages(id="chatArea")
I solved the problem with adding new an html variable. For examples
var content = '<div class = "direct-chat-msg">' +
'<div class = "direct-chat-name pull-left">' +
'<div class = "direct-chat-info clearfix">' +
'<span class = "direct-chat-name pull-left">' + data[i]["senderID"] + '</span>' +
'<span class = "direct-chat-timestamp pull-right">' + data[i]["sentDate"] + '</span>' +
'</div>' +
'<img class = "direct-chat-img" src= "/images/users/avatar04.png" alt = "resim">' +
'<div class= "direct-chat-text">'+ data[i]["message"] +'</div>' +
'</div>' +
'</div>';
var chatArea = document.getElementById("chatArea");
chatArea.innerHTML += content;

Trying to reload page after clicking similar product

Im pulling items from a JSON file. I have a class called "showProduct" and once clicked it executes a function and shows the item information on the page. I am trying to call this same function again later in my code on the similar product. I need the page to refresh with that new items contents. Below is my code really hope someone can help me out im not sure what I am doing wrong. I did not include the JSON but i hope just by looking at the class and my code someone will know why it wont work.
function openNav() {
document.getElementById("productsSideBar").style.width = "250px";
}
function closeNav() {
document.getElementById("productsSideBar").style.width = "0";
}
'use strict';
$.ajax({
dataType: "jsonp",
url: '',
success: function(json){
//check for window hash and display appropriate product category
var currentHash = window.location.hash;
switch(currentHash)
{
case '#tomatoes':
displayTomatoes();
break;
default:
displayAll();
break;
}
//display all products function
function displayAll() {
var categoryImage = '';
$.each(json, function (i, item) {
if (item.itemBrandLetter == "C") {
categoryImage += '<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12">' + '' + '<img class="img-responsive img-hover productImagesCategory" src="' + item.imageURL + '">' + '<h3>' + item.itemName + '</h3>' + '' + '</div>';
}
});
$('#imagesCategoryProducts').hide().html(categoryImage).fadeIn('slow');
//show individual product function on click
$(".showProduct").click(function(event){
//hide all current products
$('#productCategories').hide();
//get passed data from other function
var clickedItemName = '<h1>' + $(this).data('itemname') + '</h1>';
var clickedItemUPC = $(this).data('itemupc');
var clickedItemOZ = '<h2>' + $(this).data('itemoz') + '</h2>';
var clickedItemDescription = '<p>' + $(this).data('itemdescription') + '</p>';
var clickedItemImage = '<img class="img-responsive img-rounded center-block" src="' + $(this).data('itemimage') + '">';
var clickedItemGluten = $(this).data('itemgluten');
var clickedItemBPA = $(this).data('itembpa');
var clickedItemGMO = $(this).data('itemgmo');
var clickedItemPageURL = $(this).data('itempageurl');
//check if clicked data equals correct item
$.each(json, function (i, item) {
if (item.itemName === clickedItemName) {
clickedItemName
}
if (item.itemFullUPC === clickedItemUPC) {
clickedItemUPC
}
if (item.itemPackSize === clickedItemOZ) {
clickedItemOZ
}
if (item.itemDescription === clickedItemDescription) {
clickedItemDescription
}
if (item.imageURL === clickedItemImage) {
clickedItemImage
}
if (item.itemGlutenFree === clickedItemGluten) {
clickedItemGluten
}
if (item.itemBPAFree === clickedItemBPA) {
clickedItemBPA
}
if (item.itemGMOFree === clickedItemGMO) {
clickedItemGMO
}
//assign window hash to each product
if (item.itemName === clickedItemPageURL) {
event.preventDefault();
clickedItemPageURL = clickedItemPageURL.replace(/\s/g, '');
window.location.hash = clickedItemPageURL;
}
});
//remove extra characters from UPC
var originalUPC = clickedItemUPC;
var strippedUPC = '<h2>' + originalUPC.slice(1, -1); + '</h2>';
//show individual product information
$('#productSocialShare').show();
$('#individualProduct').show();
$('#relatedProducts').show();
//append product information to appropriate DIV
$('#productTitle').html(clickedItemName);
$('#productUPC').html(strippedUPC);
$('#productOZ').html(clickedItemOZ);
$('#productDescription').html(clickedItemDescription);
$('#productImage').html(clickedItemImage);
//check if gluten free is true and show image
if (clickedItemGluten == "Y") {
clickedItemGluten = '<img class="img-responsive img-rounded img-margin" src="../images/misc/gluten_free_test.jpg">';
$('#productGlutenFree').html(clickedItemGluten);
$('#productGlutenFree').show();
} else {
$('#productGlutenFree').hide();
}
//check if bpa free is true and show image
if (clickedItemBPA == "Y") {
clickedItemBPA = '<img class="img-responsive img-rounded img-margin" src="../images/misc/bpa_free_test.jpg">';
$('#productBPAFree').html(clickedItemBPA);
$('#productBPAFree').show();
} else {
$('#productBPAFree').hide();
}
//check if gmo free is true and show image
if (clickedItemGMO == "Y") {
clickedItemGMO = '<img class="img-responsive img-rounded img-margin" src="../images/misc/gmo_test.jpg">';
$('#productGMOFree').html(clickedItemGMO);
$('#productGMOFree').show();
} else {
$('#productGMOFree').hide();
}
//show random recipe for each item
var url = '';
$.getJSON(url, function(json) {
var randomRecipe = json[Math.floor(Math.random() * json.length)];
randomRecipe += '<div>' + '' + '<img class="img-responsive img-hover similarProductImagesCategory" src="' + randomRecipe.recipeImageCategoryURL + '">' + '' + '' + '<h3 class="similarProductSubCategoryImgCaption">' + randomRecipe.recipeName + '</h3>' + '' + '</div>';
$('#featuredRecipe').append(randomRecipe);
});
//show similar products
var categoryItems = [];
$.each(json, function(i, item){
if(window.location.hash.indexOf('Tomatoes') >= 0) {
if(item.itemCommodity == '1120' && item.itemBrandLetter == "C") categoryItems.push(item);
}
if(window.location.hash.indexOf('Olive') >= 0) {
if(item.itemCommodity == '2120' && item.itemBrandLetter == "C") categoryItems.push(item);
}
});
var similarProduct= '';
$.each(json, function(i,item){
similarProduct = categoryItems[Math.floor(Math.random()*categoryItems.length)];
similarProduct += '<div>' + '' + '<h3 class="similarProductSubCategoryImgCaption">' + similarProduct.itemName + '</h3>' + '' + '</div>';
});
$('#productSimilar').append(similarProduct);
});
closeNav();
}
}
});
});
<section>
<div id="productsSideBar" class="sidenav">
×
<h3>View All</h3>
Tomatoes
Sauce
Olive Oil
Red Wine Vinegar
Balsamic Vinegar
Peppers
Artichokes
Olives
Beans
Capers & Pignoli Nuts
Specialties
Spices
Fish
Broth, Stocks & Soups
Breadcrumbs
Grated Cheese
</div>
</section>
<section id="productCategories">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<br>
<span class="expandSidebar" onclick="openNav()">☰ Categories</span>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div id="imagesCategoryProducts"></div>
</div>
</div>
</div>
</section>
<!-- Product Row Start -->
<section id="individualProduct">
<div class="container topmargin">
<div class="row">
<div class="col-md-7 col-sm-6">
<!-- Product Title Div -->
<div id="productTitle"></div>
<!-- Product UPC Div -->
<div class="displayInlineBlock" id="productUPC"></div>
<span class="displayInlineBlock"><h2>•</h2></span>
<!-- Product OZ Div -->
<div class="displayInlineBlock" id="productOZ"></div>
<span class="displayInlineBlock"><h2>•</h2></span>
<!-- Where to Buy Icon -->
<div class="displayInlineBlock"><h3><span rel="popover" data-content="View Product Availability"><span class="fa-stack"><i class="fa fa-square fa-stack-2x"></i><i class="fa fa-map-marker fa-stack-1x fa-inverse"></i></span></span></h3></div>
<hr>
<!-- Product Description Div -->
<div id="productDescription"></div>
<div class="row center">
<!-- Gluten Free Div -->
<div class="displayInlineBlock" id="productGlutenFree"></div>
<!-- BPA Free Div -->
<div class="displayInlineBlock" id="productBPAFree"></div>
<!-- GMO Div -->
<div class="displayInlineBlock" id="productGMOFree"></div>
</div>
</div>
<div class="col-md-5 col-sm-6">
<!-- Product Image Div -->
<div id="productImage"></div>
</div>
</div>
</div>
</section>
<!-- Product Row End -->
<section id="relatedProducts">
<div class="container topmargin">
<div class="row">
<div class="col-md-7">
<h1 class="center">Featured Recipe</h1>
<div id="featuredRecipe"></div>
</div>
<div class="col-md-5">
<h1 class="center">Similar Product</h1>
<br>
<div id="productSimilar"></div>
</div>
</div>
</div>
</section>
Ok, there are a lot of things that are wrong in the code but I am not going to into that right now. To do what you want to achieve is rather simple, you already got all the code you need, you just need to make some adjustments to make it work.
Step one. Bind the click events to the body instead of to the element.
$("body").on('click', ".showProduct", function(event){
That way, any element on the page with the class showProduct that is clicked will trigger the function, not just the elements that were bound to when the initial function ran.
The rest is really simple, you already have the similar product's information available, you just didn't put it in the data attributes when you created the element. Now obviously there are better ways of doing this... but here is how you would do it:
similarProduct = '<div>' +
'<a href="#" class="showProduct"' +
'data-itempageurl="' + similarProduct.itemFullUPC + '"' +
'data-itemgmo="' + similarProduct.itemGMOFree + '"' +
'data-itembpa="' + similarProduct.itemBPAFree + '"' +
'data-itemgluten="' + similarProduct.itemGlutenFree + '"' +
'data-itemlowsodium="' + similarProduct.itemLowSodium + '"' +
'data-itemorganic="' + similarProduct.itemOrganic + '"' +
'data-itemimage="' + similarProduct.imageURL + '"' +
'data-itemname="' + similarProduct.itemName + '"' +
'data-itemoz="' + similarProduct.itemPackSize + '"' +
'data-itemdescription="' + similarProduct.itemDescription + '"' +
'data-itemupc="' + similarProduct.itemFullUPC + '"' + '>' +
'<img class="img-responsive img-hover similarProductImagesCategory" src="' + similarProduct.imageURL + '">' +
'<h3 class="similarProductSubCategoryImgCaption">' + similarProduct.itemName +
'</h3>' + '</a>' + '</div>';
});
That should do it... now you will notice when you click on one of the similar products it should show you the information like you wanted, however it will add the new similar product to the already existing similar product list and this will keep on growing the more you click. I am sure you can figure out how to clear the list. If not just shout.
Here is the codepen: http://codepen.io/anon/pen/oYJpve
EDIT: As a side note... normally you want to store the json data with the product id as key. Then you only save the key inside the data attribute. On click you simply use the product id (key) to access the information in your stored object.
It is really easy to do. Just create a global variable
var product_data = {};
Then you populate the object when you get the data with a function. So on success of your ajax call you could have something like this:
product_data = json;
or even better you could have a function that changes the data into the structure you want:
product_data = restructureDataFunction(json);
Then you have a nice data set which you can pull from. If you need to make updates to the dataset you can do it in one place instead of in each element.
If you want, have a look at Angular 2, it should teach you a lot and also help you with future projects. It is really strong tool especially if you have html elements representing data.

Increase number on button click

I'm trying to make an application with JSON data for a frisbee tournament. I'm now working on a page where you can view and edit the scores from a match. It should be possible to increase or decrease the score of either of the two teams. It looks like this:
I skipped some parts from the code to make it easier to read. This is the relevant code:
gamePage: function(data){
var score1 = parseInt(data.team_1_score),
score2 = parseInt(data.team_2_score);
var html = '',
html_pool_open = '<section class="new_page">';
html = html + html_pool_open;
var html_pool_top = '<div class="game">';
html = html + html_pool_top;
var html_team_1 = '<div class="name">'+data.team_1.name+'</div>'
+ '<div class="score score_team1">'
+ '<a href="#" onclick="" ><img src="/images/plus.png"/></a>'
+ '<span>'+score1+'</span>'
+ '<img src="/images/minus.png"/>'
+ '</div></div>';
The score between the span must be increased or decreased onclick
html = html + html_team_1;
x$('#content').html(html);
}
I'm not allowed to do it with jQuery, so vanilla JavaScript only please.
I would do somethig like this:
LIVE DEMO
var data = {
team_1_score: 42,
team_2_score: 6,
team_1 : {name:'Beast Amsterdam'},
team_2 : {name:'Amsterdam Money Gang'}
};
var SCORE_APP = {
tools : {
setScore : function( i, pm ){
var currScore= parseInt( data['team_'+ i +'_score'] , 10);
if(currScore=='0' && pm=='dn') return; // prevent -1 score
var newScore = data['team_'+ i +'_score'] += (pm=='up'? 1 : -1);
document.getElementById('team_'+ i +'_score').innerHTML = newScore;
}
},
game : {
gamePage : function(data) {
var html = '<section class="new_page">';
for(var i=1; i<3; i++){
html += '<div class="game"><div class="name">'+ data['team_'+i].name +'</div>'+
'<div class="score score_team1">'+
'<a href="javascript:;" onclick="SCORE_APP.tools.setScore(\''+i+'\',\'up\')">'+
'<img src="http://i.imgur.com/axk6J7M.jpg"/></a>'+
'<span id="team_'+i+'_score">'+ data['team_'+i+'_score'] +'</span>'+
'<a href="javascript:;" onclick="SCORE_APP.tools.setScore(\''+i+'\',\'dn\')">'+
'<img src="http://i.imgur.com/movjGkd.jpg"/></a>'+
'</div></div>';
}
html += '</section>';
document.getElementById('content').innerHTML = html;
}
},
init : function(){
this.game.gamePage(data);
}
};
SCORE_APP.init();
Add an ID to the span holding the score, and onclick send to the method setScore two arguments:
the team number (i = 1||2)
and the type of math we need to apply to the current score (I used a string representation "up" and "dn").
This two arguments are all you need to immediately keep up to date the data Object (holding the game stats) and apply the changes on screen to the targeted SPAN ID.
Set the onclick attribute within the <a href="#" onclick="" ></a> tag to calling a function such as increaseScore:
onclick="increaseScore()"
And give the span element an id:
<span id="myScore">
Then write a function which adds the score:
function increaseScore()
{
score1++;
document.getElementById("myScore").innerHTML=score1;
}

Categories