i am trying to Refresh div using java script . setInterval() and clearInterval (), its working fine, but i want stop Refresh process for single div when i clicked stop button ..clear Interval not working herer
<script type ="text/javascript">
$(document).ready(function () {
$('.output').click(function () {
var id = $(this).closest('.g').attr('id');
Go(id);
})
$('.bt').click(function () {
var id = $(this).closest('.g').attr('id');
stop(id)
});
function Go(id) {
id = setInterval(function () {
Chat_msg('Ch04', id, u)
}, 3000);
};
function stop(id) {
clearInterval(id);
}
})
</script>
</head>
<body>
<div id="a" class='g'>
<div class="output"></div>
<input id="Button1" type="button" value="stop" class="bt" />
</div>
<div id="b">
<div class="output"></div>
<input id="Button2" type="button" value="stop" class="bt"/>
</div>
<div id="c">
<div class="output"></div>
<input id="Button3" type="button" value="stop" class="bt" />
</div>
</body>
</html>
Use a global variable for your interval.
var interv = null;
interv = setInterval(function { ... }, 5000);
$('#btn').on('click', function(){
if (interv) clearInterval(intev);
})
It's likely the reference you associated with setInterval is not within the scope of your stop-button handler.
$("#start").on("click", function(){
var interv = setInterval(function(){ /*...*/ }, 1000);
});
$("#stop").on("click", function(){
clearInterval(interv);
});
In the code above, our interv variable is not within the scope of our #stop button handler. We could change this by moving it up another level:
var interv;
$("#start").on("click", function(){
interv = setInterval(function(){ /*...*/ }, 1000);
});
$("#stop").on("click", function(){
clearInterval(interv);
});
Now both handlers have access to the interv variable.
Looks like a combination of a scoping issue, and interchangeably using id DOM attributes with setInterval response values.
<script type ="text/javascript">
$(document).ready(function () {
var timeouts = {};
$('.output').click(function () {
var id = $(this).closest('.g').attr('id');
go(id);
});
$('.bt').click(function () {
var id = $(this).closest('.g').attr('id');
stop(id);
});
function go(id) {
timeouts[id] = setInterval(function () {
Chat_msg('Ch04', id, u)
}, 3000);
}
function stop(id) {
clearInterval(timeouts[id]);
}
});
</script>
The way I have gone about this in the past is using a function that uses a set timeout to call itself.
var stop = false
function caller () {
if (stop === true){
//do something
setTimeout(caller() , 1000);
}
else{
//do something after button has been click and stop is set to true
}
}
Related
I have tried a few things currently from what I could search online however I, unfortunately, haven't found anything.
enter image description here
I would like to disable the pagination when I click on the replace button. Since it's loading with a spinner and there is a wait I thought it would make sense to disable it but not remove it. I know how to remove, both on the css side and angularjs. However, in all honesty, I am unsure how to disable this particular feature compared to other works that I have done.
HTML:
<button class="btn btn-blue" ng-click="handleLoadAndDeactivate()"
ng-show="'Load' == importAction && 0 == errors"
title="Load">
Replace
</button>
AngularJS (Button):
$scope.handleLoadAndDeactivate = function () {
$scope.onCompleteData.targetBody.withDeactivation = true;
onComplete($scope.onCompleteData, $scope.handleLoadAndDeactivateCompleted);
};
AngularJS (Table):
$scope.operationsPreloadCompletedTableOptions = new NgTableParams({}, {
dataset: importLog
});
html
Here's how you could achive this:
(function () {
"use strict";
const app = angular.module("app", []);
app.controller("app.AppCtrl", ($scope, $timeout) => {
$scope.disablePagination = false;
$scope.handleReplace = () => {
$scope.disablePagination = true;
//Your replace logic goes here
$timeout(() => {
$scope.disablePagination = false;
}, 2000);
};
}
);
})();
body {
margin: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="app.AppCtrl">
<button ng-disabled="disablePagination"><</button>
<button ng-disabled="disablePagination">1</button>
<button ng-disabled="disablePagination">2</button>
<button ng-disabled="disablePagination">></button>
<button ng-click="handleReplace();">Replace</button>
</div>
I'm trying to achieve a file drag-and-drop with knockout.js.
This is my html:
<div type="text" id="filedrag" class="" data-bind="event: {drop: function (data,e) { $root.insertFile(e,data);} }">
<div id="messages"></div>
</div>
And this my JS:
self.insertFile = function(e, data) {
console.log("insertfile called");
var files = e.target.files || e.dataTransfer.files;
console.log(files);
};
I copied the code from a jsfiddle. I don't quite see the difference between that one and mine. What am I doing wrong?
This is because you need to have a dragover event where you cancel the default behaviour.
The cancellation of the dragover event is needed to allow drop.
See https://developer.mozilla.org/en-US/docs/Web/Events/dragover.
I have created a fiddle with your code, updated with an dragover event where you cancel default behaviour.
Fiddle: http://jsfiddle.net/JBJd2/10/
HTML:
<div type="text" id="filedrag" class="drop_zone" data-bind="event: {
drop: function (data,e) { $root.insertFile(e,data);},
dragover: function(data, e){ $root.dragover(e);}
}">
<div id="messages"></div>
</div>
JS:
self.insertFile = function(e, data) {
e.preventDefault();
console.log("insertfile called");
var files = e.target.files || e.dataTransfer.files;
console.log(files);
};
self.dragover = function(e){
e.preventDefault();
}
I am working on a asp.net MVC project. and i am using knockout.js on my view page.
I am trying to develop a data entry grid. Everything works fine except Cancel button.
If i change something on my UI ( view) and clicked on cancel , It is not showing me old values .it only show me the latest values.
Steps:
When i click on edit button it display update and cancel button.
Let us say i have edited data and click on cancel , it should not reflect on my UI.
Right now , even if you edit and click on cancel button , it is able to revert to old state.
I am not going back to old state when i clickd on cancel button.
Please suggest me some examples .
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Type Lookup....</title>
<script src="~/Scripts/jquery-2.1.0.js"></script>
<script src="~/Scripts/knockout-3.0.0.js"></script>
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<script type="text/javascript">
viewModel = {
lookupCollection: ko.observableArray()
};
//wrapper to an observable that requires accept/cancel
ko.protectedObservable = function (initialValue) {
//private variables
var _actualValue = ko.observable(initialValue),
_tempValue = initialValue;
//computed observable that we will return
var result = ko.computed({
//always return the actual value
read: function () {
return _actualValue();
},
//stored in a temporary spot until commit
write: function (newValue) {
_tempValue = newValue;
}
});
//if different, commit temp value
result.commit = function () {
if (_tempValue !== _actualValue()) {
_actualValue(_tempValue);
}
};
//force subscribers to take original
result.reset = function () {
_actualValue.valueHasMutated();
_tempValue = _actualValue(); //reset temp value
};
return result;
};
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/Home/GetIndex",
}).done(function (data) {
$(data).each(function (index, element) {
var mappedItem =
{
Id: ko.observable(element.Id),
Key: ko.observable(element.Key),
Value: ko.observable(element.Value),
Mode: ko.observable("display")
};
viewModel.lookupCollection.push(mappedItem);
});
ko.applyBindings(viewModel);
}).error(function (ex) {
alert("Error.....");
});
$(document).on("click", ".kout-edit", null, function (ev) {
var current = ko.dataFor(this);
current.Mode("edit");
});
$(document).on("click", ".kout-update", null, function (ev) {
var current = ko.dataFor(this);
saveData(current);
current.Mode("display");
});
$(document).on("click", ".kout-cancel", null, function (ev) {
var current = ko.dataFor(this);
current.Mode("display");
});
$(document).on("click", "#create", null, function (ev) {
var current = {
Id: ko.observable(0),
Key: ko.observable(),
Value: ko.observable(),
Mode: ko.observable("edit")
}
viewModel.lookupCollection.push(current);
});
function saveData(currentData) {
var postUrl = "";
var submitData = {
Id: currentData.Id(),
Key: currentData.Key(),
Value: currentData.Value()
};
if (currentData.Id && currentData.Id() > 0) {
postUrl = "/Home/Edit"
}
else {
postUrl = "/Home/Create"
}
$.ajax({
type: "POST",
contentType: "application/json",
url: postUrl,
data: JSON.stringify(submitData)
}).done(function (id) {
currentData.Id(id);
}).error(function (ex) {
alert("ERROR Saving....");
})
}
});
</script>
</head>
<body>
<div>
<p>
<button class="btn btn-primary" id="create">Create</button>
</p>
<table class="table">
<tr>
<th>Key
</th>
<th>Value
</th>
<th>Action
</th>
</tr>
<tbody data-bind="foreach: lookupCollection">
<tr data-bind="template: { name: Mode, data: $data }">
</tr>
</tbody>
</table>
<script type="text/html" id="display">
<td data-bind="text: Key"></td>
<td data-bind="text: Value"></td>
<td>
<button class="btn btn-success kout-edit">Edit</button>
<button class="btn btn-danger kout-delete">Delete</button>
</td>
</script>
<script type="text/html" id="edit">
<td>
<input type="text" data-bind="value: Key" /></td>
<td>
<input type="text" data-bind="value: Value" /></td>
<td>
<button class="btn btn-success kout-update">Update</button>
<button class="btn btn-danger kout-cancel">Cancel</button>
</td>
</script>
</div>
</body>
</html>
I have modified your code little bit.
var mappedItem =
{
Id: ko.observable(element.Id),
Key: ko.observable(element.Key),
Value: ko.observable(element.Value),
Mode: ko.observable("display"),
oldData: ko.observable()
};
I have added oldData observable to retain previous data when edit button clicked. So now when you click on cancel data will be restored by "olData" observable.
see the below code.
$(document).on("click", ".kout-edit", null, function (ev) {
var current = ko.dataFor(this);
current.oldData(ko.toJS(current));
current.Mode("edit");
});
$(document).on("click", ".kout-update", null, function (ev) {
var current = ko.dataFor(this);
current.oldData(null);
saveData(current);
current.Mode("display");
});
$(document).on("click", ".kout-cancel", null, function (ev) {
var current = ko.dataFor(this);
current.Id(current.oldData().Id);
current.Value(current.oldData().Value);
current.Key(current.oldData().Key);
current.Mode("display");
current.oldData(null);
});
Here is working example on Jsfiddle
Use this
ko.observable.fn.revertable = function () {
var self = this, originalValue = self();
if (!originalValue) {
self.subscribe(function () {
originalValue = originalValue || self();
});
}
self.commit = function () {
originalValue = self();
};
self.revert = function () {
self(originalValue || '');
};
self.isDirty = function () {
return (self() != originalValue);
};
return self;
};
and your observables like this
this.text=ko.observable().revertable();
i assume you have cancel function so in that you can do it like
this.text.revert();
and if you want to save those changes then
this.text.commit();
You have the protectedObservable in your code, but you're not using it. Turn your 'model' (the data you want to 'cancel') into a protectedObservable. On cancel, call data.reset(). On save, call data.commit().
Little example (not complete):
$(document).on("click", ".kout-cancel", null, function (ev) {
var current = ko.dataFor(this);
current.reset();
current.Mode("display");
});
$(document).on("click", "#create", null, function (ev) {
var current = ko.protectedObservable({
Id: ko.observable(0),
Key: ko.observable(),
Value: ko.observable(),
Mode: ko.observable("edit")
});
viewModel.lookupCollection.push(current);
});
I have iScroll working OK. I have added a jQuery font sizer plugin into 3 scrollable divs containing text. Upon using the "A+" to increase text size I get the "rubber band" effect [which I expected]
I am aware of MASTERING THE REFRESH() METHOD however I do not know how to implement this correctly.
My iscroll code is
var scroll1, scroll2, scroll3,
scrollNav;
function loaded() {
setTimeout(function () {
scrollNav = new iScroll('transition1', { useTransition:true });
scroll1 = new iScroll('scrollpage01', { useTransition:true });
scroll2 = new iScroll('scrollpage02', { useTransition:true });
scroll3 = new iScroll('scrollpage03', { useTransition:true });
}, 250);
}
document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
document.addEventListener('DOMContentLoaded', loaded, false);
A sample of one of the divs with text is
<article id="scrollpage01">
<div id="contentScroller">
<div class="box">
<a class="jfontsize-button" id="jfontsize-m" href="#">A-</a>
<a class="jfontsize-button" id="jfontsize-d" href="#">A</a>
<a class="jfontsize-button" id="jfontsize-p" href="#">A+</a>
<p class="some-class-name">Lorem ipsum dolor sit amet, ....blah blah blah.... suspendisse potenti.
</p>
<script type="text/javascript" language="javascript">
$('.some-class-name').jfontsize({
btnMinusClasseId: '#jfontsize-m',
btnDefaultClasseId: '#jfontsize-d',
btnPlusClasseId: '#jfontsize-p'
});
</script>
</div>
</div>
</article>
Now how/where can I add
setTimeout(function() { scroll1.refresh(); }, 0);
Oh how simple it can be.... USE the full iscroll.js and not lite and add checkDOMChanges: true
<script type="text/javascript">
var scroll1, scroll2, scroll3,
scrollNav;
function loaded() {
setTimeout(function () {
// scrollNav = new iScroll('navWrapper');
scrollNav = new iScroll('transition1', { useTransition:true });
scroll1 = new iScroll('scrollpage01', { useTransition:true, checkDOMChanges: true });
scroll2 = new iScroll('scrollpage02', { useTransition:true, checkDOMChanges: true });
scroll3 = new iScroll('scrollpage03', { useTransition:true, checkDOMChanges: true });
}, 250);
}
document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
document.addEventListener('DOMContentLoaded', loaded, false);
</script>
You can also call refresh() function whenever your Dom changes or height of Dom changes.
setTimeout(function() { scroll1.refresh(); }, 200);
Make sure that call refresh() function after iScroll loaded in Dom.
Also after dom change fully then only call refresh() function with setTimeout.
I've got a jQuery code, which
$("a.reply").click(function() {
//code
});
When I click the link with .reply class the first time, nothing happens. The second time I click, the code inside the click function works.
The link is being inserted on the page using PHP from a mysql database. so it's not being inserted dynamically.
Why is this happening? Any solution?
The BadASS Code:
$(function(){
//TextArea Max Width
var textmaxwidth = $('#wrapper').css('width');
//Initialize Focus ids To Different Initially
var oldcommentid = -1;
var newcommentid = -2;
//End Of initialization
$("a.reply").click(function() {
newcommentid = $(this).attr('id');
if (newcommentid == oldcommentid)
{
oldcommentid=newcommentid;
$("#comment_body").focus();
}
else
{
$('#comment_form').fadeOut(0, function(){$(this).remove()});
var commetformcode = $('<form id="comment_form" action="post_comment.php" method="post"><textarea name="comment_body" id="comment_body" class="added_comment_body" rows="2"></textarea> <input type="hidden" name="parent_id" id="parent_id" value="0"/> <div id="submit_button"> <input type="submit" value="Share"/><input type="button" id="cancelbutton" value="Cancel"/></div></form>');
commetformcode.hide().insertAfter($(this)).fadeIn(300);
//
var id = $(this).attr("id");
$("#parent_id").attr("value", id);
oldcommentid=newcommentid;
//dynamicformcreation function
dynarun();
//
}
return false;
});
dynarun();
function dynarun()
{
//Form Re-Run Functions
$('#comment_body').elastic();
texthover();
$("#comment_form input, select, button").uniform();
textareasizer();
$("#comment_body").focus();
$("abbr.timestamp").timeago();
return false;
}
//TextArea Resizer Function
function textareasizer(){$("#comment_body").css('max-width', textmaxwidth);return false;}
//Other Miscellaneous Functions
$('.comment-holder').hover(
function(event) {
$(this).addClass('highlight');
},
function(event) {
$('.comment-holder').removeClass('highlight');
}
);
function texthover()
{
$('.added_comment_body').hover(
function(event) {
$(this).parent().parent().addClass('highlight');
},
function(event) {
$('.comment-holder').removeClass('highlight');
}
);
return false;
}
});
This is a longshot, but are you running some sort of tracking script? Like webtrends or coremetrics (or even some of your own script, that's globally looking for all clicks)? I ran into a similar problem a while ago, where the initial-click was being captured by coremetrics. Just a thought.
Does it still happen if you comment out all your code and simply have an alert("hi") inside the click function?
Update
I think Sarfaz has the right idea, but I would use the document ready function like so
$(document).ready(function(){
$("a.reply").click(function() {
//code
});
});
I just ran into same problem and I resolved my problem by removing:
<script src="bootstrap.js"></script>
you can use bootstrap.min.js
Use Inline CSS for hiding div and use JS/jQuery to show . This way Jquery Click Event will Fire On First Click
<div class="about-block">
<div class="title">About us</div>
<div class="" id="content-text" style="display:none;">
<p>Show me.</p>
</div>
</div>
<script>
var x = document.getElementById("content-text");
jQuery( '.about-block' ).click(function() {
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
});
</script>