I want to define a function to remove element after x milliseconds.
jQuery.fn.extend({
remove: function(x) {
this.hide(x);
//this line won't work
//setTimeout(function(){ this.remove() }, x);
}
});
$("button").click(function() {
$("p").remove(600);
});
p {
background: yellow;
margin: 6px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div>
<p>Hello</p>
how are
<p>you?</p>
</div>
<button>remove</button>
After clicking the button, html looks like this:
<div>
<p style="display: none;">Hello</p>
how are
<p style="display: none;">you?</p>
</div>
<button>remove</button>
My problem is: The line: setTimeout(function(){ this.remove() }, x); didn't work. I think the compiler didn't understand what did this mean?
Can you give me any idea to call remove() function inside setTimeout?
this inside the setTimeout refers to the window object.
Use complete callback of hide()
A function to call once the animation is complete, called once per matched element.
this.hide(x, function() {
this.remove();
});
jQuery.fn.extend({
remove: function(x) {
this.hide(x, function() {
this.remove();
});
}
});
$("button").click(function() {
$("p").remove(600);
});
p {
background: yellow;
margin: 6px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div>
<p>Hello</p>
how are
<p>you?</p>
</div>
<button>remove</button>
Two issues, firstly this in the setTimeout() does not refer to the element which raised the click, but the window. You need to store the this reference in a variable within the function body. Secondly, inside the setTimeout you call remove() again, which creates a circular reference which only serves to create a new timeout. You need to change the name of the function so that remove() is still valid. Try this:
jQuery.fn.extend({
delayedRemove: function (x) {
var $el = this;
setTimeout(function(){
$el.remove()
}, x);
}
});
$("button").click(function () {
$("p").delayedRemove(600);
});
Example fiddle
No need to use timeout, you can remove the element in the done callback of hide.
jQuery.fn.extend({
remove: function (x) {
this.hide(x, function () {
this.remove();
});
}
});
Related
I added a simple function:
$.postAndVerify = function(url)
{
// this.event. ?
}
$('#myButton').click(function() {
$.postAndVerify('/url');
});
inside in it, how do I know the caller object, i.e. #myButton? Of course I know it could be just passed:
$.postAndVerify = function(url, $triggeredBy)
{
}
$('#myButton').click(function() {
$.postAndVerify('/url', $(this));
});
but it then would result tons of boilerplate code.
You could make it a plugin method by assigning the method to $.fn instead of to $
$.fn.postAndVerify = function(url){
console.log(this)// jQuery object
}
$('#myButton').click(function() {
$(this).postAndVerify('/url' );
});
Or you could use Function#bind()
You can try to use call method to pass button element as this
$.postAndVerify = function (url) {
console.log('this:');
console.log(this);
};
$('#myButton').click(function () {
$.postAndVerify.call(this, '/url');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myButton" type="button">Click me</button>
I have a code like this:
function myfunc () {
alert('executed');
}
$('.classname').on('click' function () {
myfunc();
});
I want to run myfunc once. I mean I don't want to execute it every time when user clicks on .classname element. I guess I need to warp function-calling into a condition. Something like this:
if ( /* that function never executed so far */ ) {
myfunc();
}
How can I do that?
The simplest way with jQuery is to use .one
function myfunc() {
alert('executed');
}
$('.classname').one('click', function() {
myfunc();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="classname">click here!</button>
You should remove the event listener in the function you're calling:
function myfunc () {
alert('executed');
$('.classname').off('click', myfunc);
}
$('.classname').on('click', myfunc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='classname'>Click Me</div>
Don't set a global variable like the other posts describe - there's no need for that and then you're still doing an unnecessary function call. This ensures the function is never called again and the event isn't being listed for.
$( document ).ready(function() {
var hasBeenExecuted = false;
function myfunc () {
alert('executed');
hasBeenExecuted = true;
}
$('.classname').on('click' function () {
if(!hasBeenExecuted){
myfunc();
}
});
});
var functionWasRun = false;
function myfunc () {
functionWasRun = true;
alert('executed');
}
$(document).ready(function() {
$('.classname').on('click', function () {
if (!functionWasRun) {
myfunc();
}
});
});
I would suggest, as an alternative to a global variable, assigning a property to the function.
function myfunc () {
alert('executed');
myfunc.executed = true;
}
$('.classname').on('click', function () {
if(!myfunc.executed) {
myfunc();
}
});
This has the advantage of working the same way while not polluting the global scope unnecessarily. However, if skyline3000's answer works for you, you should use that instead as it's cleaner and more sensible overall.
I am looking to hide several divs one by one or with a time interval of 5 seconds, i tried below doesn't seem to work though
<div id="container">
<div id="data1">123</div>
<div id="data2">456</div>
<div id="data3">789</div>
<div id="data4">012</div>
</div>
<script>
$('document').ready(function(){
window.setTimeout('mytimer()',5000);
});
$('document').ready(function(){
window.setTimeout('mytimer2()',10000);
});
$('document').ready(function(){
window.setTimeout('mytimer3()',15000);
});
$('document').ready(function(){
window.setTimeout('mytimer4()',20000);
});
function mytimer(){ $('#data1').hide(); }
function mytimer2(){ $('#data2').hide(); }
function mytimer3(){ $('#data3').hide(); }
function mytimer4(){ $('#data4').hide(); }
</script>
I would use single timeout function as your are hiding at regular intervals. There is one mistake in your code you need to pass the reference of function to setTimeout instead of passing the function call as a string.
Live Demo
window.setTimeout(mytimer,1000);
index = 1;
function mytimer()
{
$('#data' + (index++)).hide();
if(index <= 4) window.setTimeout(mytimer,1000);
}
You need to use $(document) instead of $('document')
$('document') will look for HTML Element with document tag, which doesn't exist.
Learn to use developer tools, Here's a good read: How to open the JavaScript console in different browsers?
Code
$(document).ready(function(){
window.setTimeout(mytimer,5000); //You can simply pass the function reference
window.setTimeout(mytimer2,10000);
window.setTimeout(mytimer3,15000);
window.setTimeout(mytimer4,20000);
});
Try it this way:
$(document).ready(function(){
window.setTimeout(mytimer, 5000);
window.setTimeout(mytimer2, 10000);
window.setTimeout(mytimer3, 15000);
window.setTimeout(mytimer4, 20000);
});
function mytimer(){
$('#data1').hide();
}
function mytimer2(){
$('#data2').hide();
}
function mytimer3(){
$('#data3').hide();
}
function mytimer4(){
$('#data4').hide();
}
Well you can use setInterval function too for this and once all the elements have been hidden you can clearInterval like one below:
DEMO HERE
function mytimer(elem){
console.log('came here');
$(elem).hide();
}
$(document).ready(function(){
var i=0;
var interval=null;
interval = window.setInterval(function(){
i++;
if(i<=$('#container').children().length)
mytimer("#data"+i);
else
{
clearInterval(interval);
return;
}
},5000);
});
Try this change and so on for the rest:
window.setTimeout(mytimer, 5000);// removed quotes and `()`
Another solution using jQuery fadeOut():
$(function() {
for (var i = 1; 4 >= i; i++)
$('#data' + i).fadeOut(5000 * i);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="container">
<div id="data1">123</div>
<div id="data2">456</div>
<div id="data3">789</div>
<div id="data4">012</div>
</div>
Use .delay() in jquery . No Settimeout function needed.
$('#data1').delay(5000).hide('fast');
$('#data2').delay(10000).hide('fast');
$('#data3').delay(15000).hide('fast');
$('#data4').delay(20000).hide('fast');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div id="data1">123</div>
<div id="data2">456</div>
<div id="data3">789</div>
<div id="data4">012</div>
</div>
There are multiple errors in your code.
You have used $('document').ready(function(){}), which is incorrect. document is a keyword, it shouldn't be in quotes.
You don't have to use multiple instance of calling $(document).ready(). You can call all your statements from a single function. You can also use $(function(){}).
While calling the function name inside the timeout function, you shouldn't put them under quotes. They act like keywords after you have defined them in your code. The function call inside the Timeout function shouldn't be followed by (). So it should be window.setTimeout(mytimer,5000);
Please refer the fiddle : http://jsfiddle.net/65gs8s9y/
I have modified your code which works fine now:
$(document).ready(function(){
window.setTimeout(mytimer,5000);
window.setTimeout(mytimer2,10000);
window.setTimeout(mytimer3,15000);
window.setTimeout(mytimer4,20000);
});
function mytimer(){
$('#data1').hide();
}
function mytimer2(){
$('#data2').hide();
}
function mytimer3(){
$('#data3').hide();
}
function mytimer4(){
$('#data4').hide();
}
I defined an object with properties and methods. But I can't find how to attach a jQuery function to a method. What I want is : when I click on the object #myTarget change its html text.
I wrote this :
function blockTest(word){
this.word = ""+genRandInt(0, 25);
this.applyNewWord = function(){
$(document).ready(function(){
$("#myTarget").click(function(){
$("#myTarget").html(this.word);
});
});
};
}
Actually, I'm trying to
Accomplishing what you want based on the code you provided isn't the way to go. I'd first create an Object rather than using a function. Insert your attributes inside that object and handle your DOM events separately:
(function($) {
var obj = {
word: "Example Word",
applyNewWord: function() {
return this.word;
}
}
$(function() {
$("#myTarget").on("click", function() {
$(this).text(obj.applyNewWord())
});
});
}(jQuery));
div {
border: 1px solid black;
cursor: pointer;
padding: 5px;
}
<div id="myTarget">Dummy Text</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
function blockTest(word){
var self = this;
self.word = ""+genRandInt(0, 25);
self.applyNewWord = function(){
$("#myTarget").click(function(){
$(this).html(self.word);
});
};
}
make copy of this and don't keep document.ready inside function
Please, help fix bug: the code currently alerts undefined instead of button's inner contents
function registerClickHandler() {
$('#clickme').click(function() {
setTimeout(function() {
alert(this.innerHTML);
}, 200);
});
}
this inside the timeout handler is not the button
function registerClickHandler() {
$('#clickme').click(function (e) {
setTimeout(function () {
alert(e.currentTarget.innerHTML);
}, 200);
});
}
Try to get the value before setTimeout
function registerClickHandler() {
$('#clickme').click(function () {
var value=this.innerHTML;
setTimeout(function () {
alert(value);
}, 200);
});
}
In java script this points to the last function and inside the timeout handler is not the button, thats why you are getting the error.
Also it's a good practice implement this kind of functions or onclicks using on.('click', function(){...})
below you can see my example:
$(document).ready(function(){
$('#clickme').on('click', function (e) {
setTimeout(function() {
alert(e.currentTarget.innerHTML);
}, 200);
});
});
You can take a look and run it here: http://jsfiddle.net/gon250/6qwk0g1t/1/
Try putting the click eventhandler outside the function. Also pass the value of 'this' to a variable before calling setTimout. Later use this variable inside setTimout. Read more about Javascrpt prototypes here
$(document).ready(function(){
$('#clickme').click(function() {
var me = this;
setTimeout(function() {
alert(me.innerHTML);
}, 200);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clickme">click me</div>