var name, logo, streaming,twitchfeed;
var users = ["freecodecamp", "medrybw", "geoffstorbeck",
"terakilobyte", "habathcx", "robotCaleb",
"thomasballinger", "noobs2ninjas", "beohoff","boonyzarc"
];
function getInfo(){
users.forEach(function(user) {
var channelURL = 'https://api.twitch.tv/kraken/channels/' + user + '?callback=?';
var streamURL = 'https://api.twitch.tv/kraken/streams/' + user + '?callback=?';
$.getJSON(channelURL, function(channel) {
$.getJSON(streamURL, function(stream) {
if (stream.stream === null) {
streaming = '<span class="label label-danger pull-right label-rawle offline"><span class="glyphicon glyphicon-thumbs-down" aria-hidden="true"></span></span>';
} else {
streaming = '<span class="label label-success pull-right label-rawle online"><span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span></span>';
}
twitchfeed = channel.url;
console.log(twitchfeed);
name = channel.display_name;
if (channel.logo === null) {
channel.logo = 'https://c1.staticflickr.com/1/186/382004453_f4b2772254.jpg';
}
logo = '<img src="' + channel.logo + '" class="logo">';
$('#person').append('<div class="user" id="' + name + '">');
$('#' + name).append(logo + '' + '<span class="name">' + name + '</span>' + '' + '</div>' + streaming);
$('#' + name).append('<div class="topic">' + stream.stream.channel.status + '</div>');
});
// what happens when tabs are clicked
$(function() {
// 'all' tab
$('#all').click(function() {
$('#all').addClass('active');
$('#online').removeClass('active');
$('#offline').removeClass('active');
$(".user").show();
});
});
// 'online' tab
$('#online').click(function() {
$('#all').removeClass('active');
$('#online').addClass('active');
$('#offline').removeClass('active');
$(".user").each(function() {
if ($(this).children(".offline").length < 1) {
$(this).show();
} else {
$(this).hide();
}
});
});
// 'offline' tab
$('#offline').click(function() {
$('#all').removeClass('active');
$('#online').removeClass('active');
$('#offline').addClass('active');
$(".user").each(function() {
if ($(this).children(".offline").length < 1) {
$(this).hide();
} else {
$(this).show();
}
});
});
});
});
}
//Trying to add a user
/*$('#submit-rawle-button').click(function(){
var $newUser = $('#newUser').val();
if(users.indexOf($newUser)==-1)
{
users.push($newUser);
}
getInfo();
});*/
getInfo();
I'm new to using JSON and the jquery $.getJSON function. If I pull all of the code out of the getInfo function and just call it once I have no problem. But maybe it's my lack of understanding but I thought if I put all that into a function. Then later I could add a button that after adding a new user to the user array. I could call the getInfo function again and it would give me a new JSON object updated with the new user that was added. However, instead I just get back empty objects. Will someone explain to me either why getInfo can't be called more than once or what my coding error is to not be getting updating JSON object.
The users.forEach is not waiting for the ajax calls to finish.I think the term is AJAX is asynchronous and the forEach is synchronous.
Keep this in mind every time you use ajax. I changed the code a bit so that it won't try to go to the next user UNTIL the second getJSON has finished.
There has to be a more elegant way to do this. I also recommend looking in to promises it will come in handy in the future. Hope this helps.
var name, logo, streaming, twitchfeed;
var users = ["freecodecamp", "medrybw", "geoffstorbeck",
"terakilobyte", "habathcx", "robotCaleb",
"thomasballinger", "noobs2ninjas", "beohoff", "boonyzarc"
];
function getInfo() {
var usersTotal = users.length;
var userCounter = 0;
function getNextUser() {
if (usersTotal > userCounter) {
var user = users[userCounter];
var channelURL = 'https://api.twitch.tv/kraken/channels/' + user + '?callback=?';
var streamURL = 'https://api.twitch.tv/kraken/streams/' + user + '?callback=?';
$.getJSON(channelURL, function (channel) {
$.getJSON(streamURL, function (stream) {
if (stream.stream === null) {
streaming = '<span class="label label-danger pull-right label-rawle offline"><span class="glyphicon glyphicon-thumbs-down" aria-hidden="true"></span></span>';
} else {
streaming = '<span class="label label-success pull-right label-rawle online"><span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span></span>';
}
twitchfeed = channel.url;
console.log(twitchfeed);
name = channel.display_name;
if (channel.logo === null) {
channel.logo = 'https://c1.staticflickr.com/1/186/382004453_f4b2772254.jpg';
}
logo = '<img src="' + channel.logo + '" class="logo">';
$('#person').append('<div class="user" id="' + name + '">');
$('#' + name).append(logo + '' + '<span class="name">' + name + '</span>' + '' + '</div>' + streaming);
$('#' + name).append('<div class="topic">' + stream.stream.channel.status + '</div>');
});
// what happens when tabs are clicked
$(function () {
// 'all' tab
$('#all').click(function () {
$('#all').addClass('active');
$('#online').removeClass('active');
$('#offline').removeClass('active');
$(".user").show();
});
});
// 'online' tab
$('#online').click(function () {
$('#all').removeClass('active');
$('#online').addClass('active');
$('#offline').removeClass('active');
$(".user").each(function () {
if ($(this).children(".offline").length < 1) {
$(this).show();
} else {
$(this).hide();
}
});
});
// 'offline' tab
$('#offline').click(function () {
$('#all').removeClass('active');
$('#online').removeClass('active');
$('#offline').addClass('active');
$(".user").each(function () {
if ($(this).children(".offline").length < 1) {
$(this).hide();
} else {
$(this).show();
}
});
});
});
}
userCounter++;
getNextUser();
}
getNextUser();
}
//Trying to add a user
/*$('#submit-rawle-button').click(function(){
var $newUser = $('#newUser').val();
if(users.indexOf($newUser)==-1)
{
users.push($newUser);
}
getInfo();
});*/
getInfo();
Related
I have function written in one js file with deferred and promise. After that I am calling that function in another HTML file where I create menu this page will work as web part. So I want to run the function after that menu generate, how can I do that.
Ph.DAL = function() {
this.getRequest = function(listName, select, filter, orderby, top, _async) {
var dfd = $.Deferred()
var request = baseRequest
request.type = 'GET'
request.async = _async
request.url =
siteAbsoluteUrl +
"/_api/web/lists/getbytitle('" +
listName +
"')/items?" +
(this.isNullOrEmpty(select) ? '' : '$select=' + select) +
'&' +
(this.isNullOrEmpty(filter) ? '' : '$filter=' + filter) +
'&' +
(this.isNullOrEmpty(orderby) ? '' : '$orderby=' + orderby) +
'&' +
(this.isNullOrEmpty(top) ? '' : '$top=' + top)
request.headers = { ACCEPT: 'application/json;odata=verbose' }
dfd = $.ajax(request)
return dfd.promise()
}
Which I am calling from another html page to generate dynamic menu
$(document).ready(function() {
var utility = new Ph.DAL()
var menuHTML = ''
utility
.getRequest(
'Navigation',
'Id,Title,Icon,URL,Target,ParentId,OrderBy',
"Active eq 'Yes'",
'',
'',
true
)
.done(function(data) {
if (data && data.d && data.d.results && data.d.results.length > 0) {
createMenu(data.d.results, null)
}
$('#respMenu').html(menuHTML)
$('#respMenu').aceResponsiveMenu({
resizeWidth: '768', // Set the same in Media query
animationSpeed: 'fast', //slow, medium, fast
accoridonExpAll: false, //Expands all the accordion menu on click
})
})
function createMenu(jSON, parentId) {
var _menu
_menu = Enumerable.from(jSON)
.where(function(value) {
return value.ParentId == parentId
})
.orderBy(function(value) {
return value.OrderBy
})
.toArray()
if (_menu.length > 0) {
_menu.map(function(item, i) {
menuHTML +=
'<li class="' +
(item.URL.toLowerCase() == utility.pageName.toLowerCase() ? 'active' : '') +
'"><a href="' +
item.URL +
'">'
menuHTML +=
'<i class="' +
item.Icon +
'"></i><span class="title">' +
item.Title +
'</span></a>'
var subMenu = Enumerable.from(jSON)
.where(function(value) {
return value.ParentId == item.Id
})
.orderBy(function(value) {
return value.OrderBy
})
.toArray()
if (subMenu.length > 0) {
createSubMenu(jSON, subMenu)
}
menuHTML += '</li>'
})
}
}
function createSubMenu(mainData, data) {
menuHTML += '<ul>'
data.map(function(item, i) {
menuHTML += '<li>' + item.Title + ''
var subMenu = Enumerable.from(mainData)
.where(function(value) {
return value.ParentId == item.Id
})
.orderBy(function(value) {
return value.OrderBy
})
.toArray()
if (subMenu.length > 0) {
createSubMenu(mainData, subMenu)
}
})
menuHTML += '</li></ul>'
}
})
Now I am trying to loop li and want to add active class on particular class but menu generated and function call is earlier so it not working. How can I do that.
Run this function after menu creation
$.menuActive = function (menuItem) {
$('#respMenu li').each(function() {
if ($(this).text() == menuItem) {
$(this).addClass('active')
return false
}
})
}
You should try to use the MutationObserver API
var mutationObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
// Do something here
});
});
mutationObserver.observe(myRefElement, {attributes: true})
//You can use custom events
//Do this after $('#respMenu').html(menuHTML)
$( "#respMenu" ).trigger( "list_ready" );
//In another file
$( "#respMenu" ).on( "list_ready", function () {
//Do ur stuff here
});
I want when my ajax detect changes on database automatically show the content in html without refresh , but it isnt doing nothing. I have to refresh the page , how can I fix it? I am trying to do ajax long polling
$(function(doc, win, $) {
var has_focus = true;
var notification = win.Notification || win.mozNotification || win.webkitNotification;
var $badge = $("#notifications-badge");
var $list = $("#notifications-list");
var $button = $("#notifications-button");
URL_GET_NOTIFICATION = BASE_URL + 'notify/pusher';
URL_GET_NOTIFICATION_UPDATE = BASE_URL + 'notify/update';
if ('undefined' === typeof notification) {
console.log('Web notification not supported');
} else {
notification.requestPermission(function(permission) {});
}
function check_notifications(timestamp) {
$.ajax({
type: 'GET',
url: URL_GET_NOTIFICATION,
data: { timestamp : timestamp },
dataType: 'json',
async: true,
success: function (data) {
for (var i in data.notifications) {
notify(data.notifications[i].message, data.notifications[i].type, data.notifications[i].timestamp);
}
check_notifications(data.timestamp);
}
});
}
function notify(message, type, created_at) {
var type_txt = 'info';
var url = '#';
var icon = 'info-circle';
if (type == 0) {
type_txt = 'success';
icon = 'check';
} else if (type == 1) {
type_txt = 'info';
icon = 'exclamation';
} else if (type == 2) {
type_txt = 'warning';
icon = 'exclamation-triangle';
} else if (type == 3 || type == 4) {
type_txt = 'danger';
icon = 'fire';
}
$badge.show();
$badge.text(parseInt($badge.text()) + 1);
$list.find(".item").eq(13).nextAll(".item").remove();
var item = '<li class="item text-' + type_txt + '"><a href="' + url + '"><span class="text-' + type_txt + '">' +
'<i class="fa fa-' + icon + ' fa-fw"></i> ' + message.substr(0, 22) + '</span>' +
'<span class="pull-right text-muted small" data-time="' + created_at + '">X</span></a></li>' +
'<li class="item divider"></li>';
$list.prepend(item);
$('.dropdown.open .dropdown-toggle').dropdown('toggle');
return true;
}
$(win).on("blur", function () {
has_focus = false;
});
$(win).on("focus", function () {
has_focus = true;
});
$button.on("click", function () {
$badge.fadeOut(300, function () {
$badge.text(0);
});
$list.find("span[data-time]").each(function (index) {
var $this = $(this);
$this.text(moment.unix($this.data('time')).fromNow());
});
});
check_notifications();
}(document, window, jQuery));
I Follow This Article for Impalement CRUD Operation with HTML5 and Javascript.
So that Submit Data to Local Storage and save it.
my problem is Delete and Edit Operation when clicking on delete and edit button Nothing happens.
Javascript
$(function () {
var operation = "A";
var selected_index = -1;
var tbClients = localStorage.getItem("tbClients"); //Retrieve the stored data
tbClients = JSON.parse(tbClients); //Converts string to object
if (tbClients === null) //If there is no data, initialize an empty array
tbClients = [];
function Add() {
debugger;
var Data = {
ExternalProjects: {
Name: $('#Name').val(),
Body: $('#Body').val(),
Url: $('#Url').val()
}
};
tbClients.push(Data);
localStorage.setItem("tbClients", JSON.stringify(tbClients));
alert("The data was saved.");
List();
return true;
}
function Edit() {
tbClients[selected_index] = JSON.stringify({
Name: $('#Name').val(),
Body: $('#Body').val(),
Url: $('#Url').val()
}); //Alter the selected item on the table
localStorage.setItem("tbClients", JSON.stringify(tbClients));
operation = "A"; //Return to default value
return true;
}
function List() {
debugger;
var div = $('div#ExProjectList');
div.html("");
var cli = tbClients;
for (var i = 0; i < cli.length; i++) {
debugger;
div.append(
'<div href="#" class="list-group-item list-group-item-action flex-column align-items-start">' +
'<div class="d-flex w-100 justify-content-between">' +
' <h5 class="mb-1">' + cli[i].ExternalProjects.Name + '</h5>' +
' <small>' +
'<a id="btnDelete" alt="Delete' + i + '"><i class="fa fa-trash" style="cursor: pointer" ></i></a>' +
'<a id="btnEdit" alt="Edite' + i + '"><i class="fa fa-pencil" style="cursor: pointer"></i></a>'
+ '</small>' +
' </div>' +
'<p class="mb-1">' + cli[i].ExternalProjects.Body + '</p>' +
'<small>' + cli[i].ExternalProjects.Url + '</small>' +
'</div>'
);
}
}
function Delete() {
tbClients.splice(selected_index, 1);
localStorage.setItem("tbClients", JSON.stringify(tbClients));
}
$('#btnDelete').bind('click', function() {
selected_index = parseInt($(this).attr("alt").replace("Delete", ""));
Delete();
List();
});
$("#btnEdit").bind("click", function() {
operation = "E";
selected_index = parseInt($(this).attr("alt").replace("Edit", ""));
var cli = JSON.parse(tbClients[selected_index]);
$("#Name").val(cli.ExternalProjects.Name);
$("#Body").val(cli.ExternalProjects.Body);
$("#Url").val(cli.ExternalProjects.Url);
});
$("#AddExternalProject").click(function () {
if (operation === "A"){
return Add();
}
else{
return Edit();
}
});
});
You are creating the HTML dynamically, but not attaching the event to the element.
Instead of using:
$('#btnDelete').bind('click', function() {
selected_index = parseInt($(this).attr("alt").replace("Delete", ""));
Delete();
List();
});
$("#btnEdit").bind("click", function() {
operation = "E";
selected_index = parseInt($(this).attr("alt").replace("Edit", ""));
var cli = JSON.parse(tbClients[selected_index]);
$("#Name").val(cli.ExternalProjects.Name);
$("#Body").val(cli.ExternalProjects.Body);
$("#Url").val(cli.ExternalProjects.Url);
});
Use event delegation:
$("#ExProjectList").on("click", "#btnDelete", function() {
selected_index = parseInt($(this).attr("alt").replace("Delete", ""));
Delete();
List();
});
$("#ExProjectList").on("click", "#btnEdit", function() {
operation = "E";
selected_index = parseInt($(this).attr("alt").replace("Edit", ""));
var cli = JSON.parse(tbClients[selected_index]);
$("#Name").val(cli.ExternalProjects.Name);
$("#Body").val(cli.ExternalProjects.Body);
$("#Url").val(cli.ExternalProjects.Url);
});
If you are binding any event to any html element, always bind inside
$(document).ready(function(){
//code here
});
Because if you add the script earlier before Dom Content is ready, in self calling function then those elements will not be available to bind the events.
I added a delete function to a todo list app that i built. The delete function works; however, when I refresh the page all the items that i deleted come back. How can I remove the items permanently from the database?
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
//////this section works
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
///////this does not want to remove the item from the database
$.destroy("/tasks/" + itemId, {
_method: "destroy",
task: {
done: doneValue
}
});
});
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
// still dont understand this
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
var li_to_delete = $('.todo-list li.completed');
$.ajax({
type: 'DELETE',
url: "/tasks" + li_to_delete,
success: function(){
li_to_delete.remove();
}
});
});
});
i changed the code but im not sure how to properly extract the url.
I am trying to use JavaScript & jQuery to overwrite standard functionality - namely alert and confirm.
For this, I have built something that shows a dialog when an alert or confirm is asked for by the code, and this looks like:
function throwError(e_content) {
var e_title = "Error";
var e = errordiv;
var return_error = e.start + e.header_start + e_title + e.header_end + e.body_start + e_content + e.body_end + e.end;
jQuery("body").append(return_error);
return;
}
function throwConfirm(e_content) {
function confirmCallback() {
var retval = "213";
jQuery("body").on("click", function (e) {
if (e.target.id == "confirm_okay") {
hideError();
retval = true;
}
else if (e.target.id == "confirm_cancel") {
hideError();
retval = false;
}
})
retval == "213" ? confirmCallback() : retval;
return retval;
}
var e_title = "Confirm Action";
var e = confirmdiv;
var return_error = e.start + e.header_start + e_title + e.header_end + e.body_start + e_content + e.body_end + e.end;
jQuery("body").append(return_error);
return confirmCallback();
}
function hideError () {
jQuery(document).find(".custom_error_div").remove();
return;
}
var errordiv = {
start: '<div class="custom_error_div"><div class="custom_error_div_content" >',
end: '</div></div>',
header_start: '<div class="custom_error_div_header">',
header_end: '</div>',
body_start: '<div class="custom_error_div_body">',
body_end: '<div class="bottom-buttons">'
+ '<button id="alert_okay">Ok</button>'
+ '</div>'
};
var confirmdiv = {
start: '<div class="custom_error_div"><div class="custom_error_div_content" >',
end: '</div></div>',
header_start: '<div class="custom_error_div_header">',
header_end: '</div>',
body_start: '<div class="custom_error_div_body">',
body_end: '<div class="bottom-buttons">'
+ '<button id="confirm_okay">Ok</button><button id="confirm_cancel">Cancel</button>'
+ '</div>'
};
The basis of this is working, it alerts and confirms when I want it to - but the confirm is an issue, when clicking either "Yes" or "No", the throwConfirm function is supposed to return true or false and this doesn't seem to be happening, instead, I reach maximum call size.
The basis behind doing this are complex and convoluted and not relevant to the question at hand - what I need to know is:
How do I get the throwConfirm function to return true or false based on what button the user clicks?
This shows one way of doing it. It's kind of kludgy - there's going to be a better way of setting the callback instead of using the global _callback variable
"use strict";
function throwError(e_content) {
var e_title = "Error";
var e = errordiv;
var return_error = e.start + e.header_start + e_title + e.header_end + e.body_start + e_content + e.body_end + e.end;
jQuery("body").append(return_error);
return;
}
function throwConfirm(e_content, callback) {
hideError();
var e_title = "Confirm Action";
var e = confirmdiv;
var return_error = e.start + e.header_start + e_title + e.header_end + e.body_start + e_content + e.body_end + e.end;
jQuery("body").append(return_error);
// this is a hack, but I'm tired
_callback = callback
}
function hideError () {
jQuery(document).find(".custom_error_div").remove();
return;
}
var errordiv = {
start: '<div class="custom_error_div"><div class="custom_error_div_content" >',
end: '</div></div>',
header_start: '<div class="custom_error_div_header">',
header_end: '</div>',
body_start: '<div class="custom_error_div_body">',
body_end: '<div class="bottom-buttons">'
+ '<button id="alert_okay">Ok</button>'
+ '</div>'
};
var confirmdiv = {
start: '<div class="custom_error_div"><div class="custom_error_div_content" >',
end: '</div></div>',
header_start: '<div class="custom_error_div_header">',
header_end: '</div>',
body_start: '<div class="custom_error_div_body">',
body_end: '<div class="bottom-buttons">'
+ '<button id="confirm_okay">Ok</button><button id="confirm_cancel">Cancel</button>'
+ '</div>'
};
var _callback;
function init() {
jQuery("body").on("click", function (e) {
if (e.target.id == "confirm_okay") {
hideError();
_callback( true );
}
else if (e.target.id == "confirm_cancel") {
hideError();
_callback( false );
}
})
$(document).on("click", "#foo", function() { throwConfirm("bar", doSomethingWithMyRetval) } );
}
function doSomethingWithMyRetval(foo) {
// foo foo foo
console.log("The retval from the confirm was: "+foo);
}
$(document).ready(init);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<body>
<input id="foo" type="button">
</body>