(window).scrollTop function doesn't fire at first click - javascript

I have a bar chart which is clickable, and when its clicked, it fires mainQuestBarClick function. In this function, I have this line $(window).scrollTop($('#scrollHere').offset().top); to scroll to scrollHere div. When I click to the bar, it doesn't scroll there but at second time I click it, it scrolls. What could be the reason?
Here is the function:
var mainQuestBarClick = function (event, pos, obj) {
if (!obj)
return;
$(window).scrollTop($('#scrollHere').offset().top);
//goToByScroll($("#scrollHere").attr("id"));
var selectedBranchName = encodeURIComponent(obj.series.label);
$("#SelectedBranchFromBarChart").val(selectedBranchName);
$("#content").block();
//Stats Chart
$.ajax({
type: "GET",
url: '#Url.Action("GetStatsForSpecificBranch", "SurveyReports")',
data: "BranchName="+encodeURIComponent(obj.series.label)+"&SurveyId=" + $("#SurveyId").val() + "&startDate=" + $("#ReportStartDate").val() + "&endDate=" + $("#ReportEndDate").val(),
cache: false,
success: function (r) {
if (r.success == false) {
noty({ text: r.resultText, type: 'error', timeout: 2000, modal: true });
} else {
$("#statboxSurveyCountTitle").html("<b>" + selectedBranchName + "</b> Şubesi Anket Sayısı");
$("#statboxSurveyAvgTitle").html("<b>" + selectedBranchName + "</b> Şubesi Anket Ortalaması");
$("#statboxSurveyRecommTitle").html("<b>" + selectedBranchName + "</b> Şubesi Tavsiye Oranı")
$("#StatboxesDiv").show();
$("#SurveyCountVal").text(r.FilledSurveyCount);
$("#SurveyAvgVal").text(r.FilledSurveyAverageRating.toFixed(2));
$("#SurveyRecommVal").text("%"+r.RecommendYesPercent);
}
},
error: function (error) {
noty({ text: "Bir hata oluştu lütfen tekrar deneyiniz!", type: 'error', timeout: 2000, modal: true });
}
});
$("#content").unblock();
}

This is a late solution to this problem but somehow I managed to do what I want to do. Here is how I solved the problem:
I created a function which takes the id of the element to be scrolled:
function goToByScroll(id){
#{int scroll = 600;
if(Model.BranchList.Count <= 1)
{
scroll = 750;
}
}
// Scroll
$('html,body').animate({scrollTop:#scroll}, 1000);
}
And changed this part in my code above in the question:
$(window).scrollTop($('#scrollHere').offset().top);
to this:
goToByScroll($("#scrollHere").attr("id"));

Related

How can I add condition when pickdate called?

My html like this :
<input id="appdate" type="text" class="required" placeholder="Select Date">
My javascript like this :
...
$(document).ready(function () {
...
$('#appdate').change(function () {
console.log('when the retrieveSchedule function is called, this is not executed')
var date = $('#appdate').val();
...
});
});
appointment = function () {
function retrieveSchedule({ id, url }) {
...
$.ajax({
url: url,
type: 'GET',
data: '',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
...
var $input = $('#appdate').pickadate({
disable: _disableDate,
formatSubmit: 'yyyy-mm-dd',
min: someDate,
max: new Date((someDate.getFullYear() + 1), (someDate.getMonth() - 1), someDate.getDate()),
selectMonths: true,
selectYears: true,
close: 'Ok',
autoClose: false,
closeOnSelect: false, // Close upon selecting a date,
onClose: function () { $('.picker__input').removeClass('picker__input--target'); $('.picker').blur(); },
onRender: function () {
$('#appdate_root .picker__day-display').append('<div class="cal-notif"></div>');
var loadingcal = '<div class="cal-loading preloader-background">' +
'<div class="preloader-wrapper big active center">' +
'<div class="spinner-layer spinner-blue-only">' +
'<div class="circle-clipper left">' +
'<div class="circle"></div>' +
'</div>' +
'<div class="gap-patch">' +
'<div class="circle"></div>' +
'</div>' +
'<div class="circle-clipper right">' +
'<div class="circle"></div>' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
$('#appdate_root .picker__calendar-container').append(loadingcal);
}
});
// Use the picker object directly.
var picker = $input.pickadate('picker');
picker.clear();
if (picker.get('start')) {
var getdisable = picker.get('disable');
picker.set('enable', [1, 2, 3, 4, 5, 6, 7]);
picker.set('disable', _disableDate);
getdisable = picker.get('disable');
picker.render();
} else { console.log('false picker'); }
},
error: function (result) {
...
}
}).done(function () {
...
});
}
return { retrieveSchedule: retrieveSchedule }
}();
I don't display all my scripts. I only show the details of the problem I am having
When the above js file is run, it will first call the retrieveSchedule function. If ajax is successful, it will create a pickdate and display it in the input text with id = appdate
My problem is that when pickdate is successfully displayed in the input text with id = appdate, it also runs this script in $('#appdate').change(function({. I want the statement inside $('#appdate').change(function({ is not run. So it only runs when selecting pickdate. Not display pickdate
How do I make the conditions?
How about create checking variable like this
var appdateCreated = false;
$('#appdate').change(function () {
if(appdateCreated) {
console.log('when the retrieveSchedule function is called, this is not executed')
} else {
appdateCreated = true
}
});

ESRI WAB custom widget popup disappears after 1 second

I am working on an in-panel custom widget for our WebApp on ESRI. When the widget is active the map is listening to mouse click events. When fired, a REST service is called via ajax and the result will be displayed in a popup.
If there is no other layer like WMS/WFS active everything is working fine. But with another active layer, the popup appears for a second and then disappears.
Any idea?
define(['dojo/_base/declare', 'jimu/BaseWidget', 'esri/layers/layer', 'dojo/dom-construct', 'esri/geometry/webMercatorUtils', 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'],
function(declare, BaseWidget, Layer, domConstruct, webMercatorUtils) {
var map;
return declare([BaseWidget], {
baseClass: 'jimu-widget-myTest',
name: 'myTest',
customPopup: new Popup({
offsetX: 10,
offsetY: 10,
visibleWhenEmpty: true
},domConstruct.create("div")),
startup: function() {
map = this.map;
this.map._mapParams.infoWindow = this._customPopup;
},
onOpen: function(){
document.getElementById(this.map.id).addEventListener("click", myClickListener);
},
onClose: function(){
document.getElementById(this.map.id).removeEventListener("click", myClickListener);
}
});
function myClickListener(evt) {
if(evt.mapPoint) {
var content = "";
var mp = webMercatorUtils.webMercatorToGeographic(evt.mapPoint);
lon = mp.x;
lat = mp.y;
var service_url = "xxxxxx";
$.ajax({
method: 'GET',
url: service_url,
dataType: 'json',
error: function() {
console.log("Could not load data.");
},
success: function(result) {
for(var i = 0; i < result.values.length; i++) {
content += "<div class='test'>";
content += "<table style='width:100%'><tr><td><b>bli</b></td><td>" + result.values[i].bli + "</td></tr>" +
"<tr><td><b>bla</b></td><td>" + result.values[i].bla + "</td></tr>" +
"<tr><td><b>blub</b></td><td>" + result.values[i].blub + "</td></tr>";
content += "</table></div>";
}
map.infoWindow.setTitle("myTest");
map.infoWindow.setContent(content);
map.infoWindow.show(evt.screenPoint);
}
});
}
}
});
Problem solved by adding the Listener this way
onOpen: function(){
map.on("click", myClickListener);
},
and not like this
onOpen: function(){
document.getElementById(this.map.id).addEventListener("click", myClickListener);
},

How to call loadmore function(only once) on scroll down javascript function?

i am using the following code to trigger my onloadmore funciton when user scroll down and reaches bottom of page. But i notice that many times the function get called multiple times on scroll down! could any one tell me why loadmore function get called more then once for same set of data! is it internet connection problem ? I just want loadmore called only once!
<script>
var nextTagId = null;
function callLoadMore() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "http://api.sometime.com/api.php?count=100" + ( nextTagId ? "&next_id=" + nextTagId : ""),
success: function(data) {
for (var i = 0; i < 100; i++) {
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].pics.standard.path+'\n' ;
}
}
});
}
</script>
<script>
$(function() {
$(window).bind("scroll", function (){
console.log("SCROLL : " + $(window).scrollTop()
+ " - " + $(window).innerHeight()
+ " - " + document.body.clientHeight);
if ($(window).scrollTop() + document.body.clientHeight >= $(window).innerHeight()) {
//alert('Bottom!');
callLoadMore();
}
});
});
</script>

.json not showing in Safari, jQuery plugin

I created a jQuery plugin that shows up in Chrome as expected, but in Safari, it is not loading the following URL so the badges are showing up: https://www.codeschool.com/users/audreyklammer.json
I think this is the issue. Any ideas on either what I should console.log or does anything stand out? I will do the work just would love your input.
Here is the full code on my GitHub but also pasted below:
https://github.com/Klammertime/Badge-Widget/blob/master/dist/js/jquery.insignia.js
;(function($) {
$(document).ready(function() {
var insigniaList = $('.insignia');
for(var i = 0; i < insigniaList.length; i++){
var insigniaEntry = insigniaList[i];
console.log(insigniaEntry);
$(insigniaEntry).insignia(insigniaEntry.dataset.treehouse, insigniaEntry.dataset.codeschool);
}
});
$.fn.insignia = function(usernameTreehouse, usernameCodeschool) {
this.empty();
if (usernameTreehouse) {
getBadges(usernameTreehouse, this);
}
if (usernameCodeschool) {
getBadges2(usernameCodeschool, this);
}
}
function getBadges(usernameTreehouse, element) {
$.ajax({
url: "http://teamtreehouse.com/" + usernameTreehouse + ".json",
type: "GET",
crossDomain: true,
dataType: "json",
async: true,
success: function(dataBack) {
var badges = dataBack.badges;
$(element).append("<h3>I have taken " + badges.length + " lessons and scored " + dataBack.points.total +
" points at Treehouse!</h3><div class=\"badges\"></div>");
badges.forEach(function(badge, i) {
if (i < 7) {
element.find(".badges").append("<li class=\"badgeImages\"> <img src=' " + badge.icon_url + " '/></li>");
}
});
},
error: function(dataBack) {
console.log("something went wrong.");
//this happen when call fails
}
});
}
function getBadges2(usernameCodeschool, element) {
$.ajax({
url: "https://www.codeschool.com/users/" + usernameCodeschool + ".json",
type: "GET",
crossDomain: true,
dataType: "jsonp",
async: true,
success: function(dataBack) {
console.log(dataBack);
$(element).append("<h3>I have taken " + dataBack.badges.length + " lessons and scored " + dataBack.user.total_score +
" points at Codeschool!</h3><div class=\"badges2\"></div>");
var badge = dataBack.badges;
console.log(badge);
badge.forEach(function(badge, i) {
if (i < 7) {
element.find(".badges2").append("<li class=\"badgeImages\"> <img src=' " + badge.badge + " '/></li>");
}
});
},
error: function(dataBack) {
console.log("something went wrong.");
//this happen when call fails
}
});
}
}(jQuery));

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