run function after element generated jquery - javascript

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
});

Related

Search Results goes up when scrolling down in JavaScript

I have a search box where users can search for products. This drop down shows all of the products. I am trying to Scroll down the list using scroller but when i scroll down it goes up
if ($('#search_product').length) {
//Add Product
$('#search_product')
.autocomplete({
source: function(request, response) {
var price_group = '';
var search_fields = [];
$('.search_fields:checked').each(function(i){
search_fields[i] = $(this).val();
});
if ($('#price_group').length > 0) {
price_group = $('#price_group').val();
}
$.getJSON(
'/products/list',
{
price_group: price_group,
location_id: $('input#location_id').val(),
term: request.term,
not_for_selling: 0,
search_fields: search_fields
},
response
);
},
minLength: 2,
response: function(event, ui) {
if (ui.content.length == 1) {
ui.item = ui.content[0];
if ((ui.item.enable_stock == 1 && ui.item.qty_available > 0) ||
(ui.item.enable_stock == 0)) {
$(this)
.data('ui-autocomplete')
._trigger('select', 'autocompleteselect', ui);
$(this).autocomplete('close');
}
} else if (ui.content.length == 0) {
toastr.error(LANG.no_products_found);
$('input#search_product').select();
}
},
focus: function(event, ui) {
if (ui.item.qty_available <= 0) {
return false;
}
},
select: function(event, ui) {
var searched_term = $(this).val();
var is_overselling_allowed = false;
if($('input#is_overselling_allowed').length) {
is_overselling_allowed = true;
}
if (ui.item.enable_stock != 1 || ui.item.qty_available > 0 || is_overselling_allowed) {
$(this).val(null);
//Pre select lot number only if the searched term is same as the lot number
var purchase_line_id = ui.item.purchase_line_id && searched_term == ui.item.lot_number ? ui.item.purchase_line_id : null;
pos_product_row(ui.item.variation_id, purchase_line_id);
} else {
alert(LANG.out_of_stock);
}
},
})
.autocomplete('instance')._renderItem = function(ul, item) {
var is_overselling_allowed = false;
if($('input#is_overselling_allowed').length) {
is_overselling_allowed = true;
}
if (item.enable_stock == 1 && item.qty_available <= 0 && !is_overselling_allowed) {
var string = '<li class="ui-state-disabled">' + item.name;
if (item.type == 'variable') {
string += '-' + item.variation;
}
var selling_price = item.selling_price;
if (item.variation_group_price) {
selling_price = item.variation_group_price;
}
string +=
' (' +
item.sub_sku +
')' +
'<br> Price: ' +
selling_price +
' (Out of stock) </li>';
return $(string).appendTo(ul);
} else {
var string = '<div class="col-md-10">' + item.name;
if (item.type == 'variable') {
string += '-' + item.variation;
}
var selling_price = item.selling_price;
if (item.variation_group_price) {
selling_price = item.variation_group_price;
}
string += ' (' + item.sub_sku + ')' + '<br> Price: ' + selling_price;
if (item.enable_stock == 1) {
var qty_available = __currency_trans_from_en(item.qty_available, false, false, __currency_precision, true);
string += ' - ' + qty_available + item.unit;
}
string += '</div>';
string += '<div class="col-md-2" style="text-align:right"> <img src="' + item.image_url + '" width="100" hight="100"> </div>';
return $('<li>')
.append(string)
.appendTo(ul);
}
};
}
Am not sure where am going wrong. Any help is appreciated. when i try to scroll down it allows scrolling but it goes to top instantly top first few results
Thanks in advance.
Laravel Blade Code
{!! Form::text('search_product', null, ['class' => 'form-control mousetrap', 'id' => 'search_product', 'placeholder' => __('lang_v1.search_product_placeholder'),
'disabled' => is_null($default_location)? true : false,
'autofocus' => is_null($default_location)? false : true,
]); !!}

why my ajax makes me to refresh my page to see content?

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));

delete from database with javascript

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.

Appending content from RSS feeds to separate divs

I'm trying to display RSS using the following JS code. But when I execute this, both the RSS feeds are changed to same content (the one that is execute later) and all the feeds are appended to the same div. I think rss = this is causing the problem. Any workaround ?
HTML:
<div id="rss1" class="rss-widget">
<ul></ul>
</div>
<div id="rss2" class="rss-widget">
<ul></ul>
</div>
<div id="rss3" class="rss-widget">
<ul></ul>
</div>
JS:
function RSSWidget(id, url) {
rss = this;
rss.FEED_URL = url;
rss.JSON = new Array();
rss.widgetHolder = $('#' + id + ' ul ');
rss.storiesLimit = 15;
rss.renderBlogItem = function (object) {
var item = '<li class="blog-item">';
item += '<a href="' + object.link + '">';
item += '<div class="blog-item-title">' + object.title + '</div>';
item += '<div class="blog-item-author">' + object.author + '</div>';
// item += '<div class="blog-item-content">' + object.content + '</div>';
item += '</a>'
item += '</li>';
rss.widgetHolder.append(item);
}
return $.ajax({
url: 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(rss.FEED_URL),
dataType: 'json',
success: function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
rss.JSON.push({ //add objects to the array
title: e.title,
author: e.author,
content: e.content || "",
link: e.link
});
});
if (rss.storiesLimit > rss.JSON.length)
rss.storiesLimit = rss.JSON.length;
for (var i = 0; i < rss.storiesLimit; i++) {
rss.renderBlogItem(rss.JSON[i]);
}
$('#' + id + ' li ').each(function () {
var delay = ($(this).index() / rss.storiesLimit) + 's';
$(this).css({
webkitAnimationDelay: delay,
mozAnimationDelay: delay,
animationDelay: delay
});
});
}
}
});
}
$.when(RSSWidget('rss1', "http://rss.cnn.com/rss/money_markets.rss"))
.then(function () {
RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews")
})
.then(function () {
RSSWidget('rss3', "http://finance.yahoo.com/rss/topfinstories")
});
.then(RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews"));
is immediately invoked. Try calling second RSSWidget within .then() anonymous function
.then(function() {
RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews")
})
Also, no promise is returned from RSSWidget; you can include return $.ajax(/* settings */) from RSSWidget to return the jQuery promise object from RSSWidget.

problem ajax load with autocomplete.?

i created a jquery autocomplete it work true, but loading LOADING... it after removed value by Backspace don't work true. it not hide and Still is show.
how can after removed value by Backspace, hide LOADING... ?
EXAMPLE: Please click on link and see problem
my full code:
$(document).ready(function () {
/// LOADING... ///////////////////////////////////////////////////////////////////////////////////////
$('#loadingDiv')
.hide() // hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
});
/// autocomplete /////////////////////////////////////////////////////////////////////////////////////////
$('.auto_complete').keyup(function () {
var specific = '.' + $(this).closest('div.auto_box').find('b').attr('class');
var cl_list = '.' + $(this).closest('div.auto_box').find('ul').attr('class');
var id = '#' + this.id;
var url = $(id).attr('class');
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
dataType: 'json',
url: url,
data: dataObj,
cache: false,
success: function (data) {
//alert(url)
var cl_list = '.' + $('.auto_box '+ specific +' ul').attr('class');
var id_name = $(cl_list).attr('id');
$(cl_list).show().html('');
if (data == 0) {
$(cl_list).show().html('<p><b>There is no</b></p>');
}
else {
$.each(data, function (a, b) {
//alert(b.name)
$('<p id="' + b.name + '">' + b.name + '</p>').appendTo(cl_list);
});
$(cl_list + ' p').click(function (e) {
e.preventDefault();
var ac = $(this).attr('id');
$('<b>' + ac + '، <input type="text" name="'+id_name+'[]" value="' + ac + '" style="border: none; display: none;" /></b>').appendTo($('.auto_box ' + specific + ' span'));
$(this).remove();
return false;
});
$('.auto_box span b').live('click', function (e) {
e.preventDefault();
$(this).remove();
return false;
});
}
if ($(specific + ' input').val() == '') {
$(cl_list + " p").hide().remove();
$(cl_list).css('display','none');
$(".list_name").show().html('');
};
$('body').click(function () {
$(cl_list + " p").hide().remove();
$('.auto_complete').val('');
$(cl_list).show().html('');
$(cl_list).css('display','none')
});
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
});
I recommend you to use jsfiddle next time you post code examples in a link.
Nevermind. The "loading" message keeps there because there's no fallback to empty values on results.
A quick fix could be just by test that there's a value in the input before making any post like if(this.value == ""){
$(cl_list).css('display', 'none');
return false;
}
Here's how it works with it

Categories

Resources