Alert button's inner content after clicking it - javascript

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>

Related

delay a function call on button click - javascript

I am attempting to delay a function call on button click using javascript in a manner when you click the button it should delay for like 3 or 5 seconds before calling the function. This is my snippet:
jQuery(document).ready(function(){
$('#myButton').on('click', myFunction);
setTimeout(function() {
myFunction();
}, 5000);
function myFunction() {
var text = $(".total").text();
alert(text);
}
});
How can I get it right such that the function is called only when the button is clicked with a delay of 5 seconds?
You can try below code, I done some changes in your code snippet :
jQuery(document).ready(function(){
$('#myButton').on('click', function(){
setTimeout(myFunction, 5000);
});
function myFunction() {
var text = $(".total").text();
alert(text);
}
});
The issue is because you're providing the reference to myFunction() to the click handler, hence it's called immediately.
Instead you need to put the setTimeout() call in an anonymous function that you provide to the click. You also need to place the myFunction() definition in scope of the window so that it's available from the setTimeout() call. Try this:
$(function() {
$('#myButton').on('click', function() {
setTimeout(myFunction, 5000);
});
});
function myFunction() {
var text = $(".total").text();
alert(text);
}
jQuery(document).ready(function(){
$('#myButton').on('click', myFunction);
function myFunction() {
setTimeout(function(){
var text = $(".total").text();
alert(text);
}, 5000);
}
});

Move element with jQuery plugin - setInterval

Why this code doesn't work?
I wrote This code but:
(function($){
$.fn.newsSlider = function() {
setTimeout(function() {
this.each( function() {
$(this).each(function(){
$(this).append($(this).children(":first-child").clone());
$(this).children(":first-child").remove();
});
});
}, 3000);
}
}(jQuery));
With setInterval:
http://jsfiddle.net/OmidJackson/46UNg/
Without setInterval:
http://jsfiddle.net/OmidJackson/6bKWU/
Your problem is that this has different meaning (the window object) inside the setTimeout function literal. Check this answer for further info about this in different contexts.
The solution is to save a reference to this so you can use it inside the setTimeout.
See this example.
You need to store the this as it currently has a value of window
var $this = this;
setTimeout(function() {
$this.each( function() {
$(this).each(function(){
$(this).append($(this).children(":first-child").clone());
$(this).children(":first-child").remove();
});
});
}, 3000);

Calling a function (ex. namespace.show) by name

I want to call a function with a namespace based on its name.
Perhaps some background: What I want is, dynamically bind pages via $.mobile.loadPage(inStrUrl, { showLoadMsg: false }); and then, based on the current page, invoke a function within a loaded page. For example: each page has a showFilter function, the Event is attached to a main.html - page which should call the matching function in the current page.
I also tried some solutions, with jquery too, but nothing works for me.
This is my function code:
function namespace() { }
namespace.showFilter = function () {
alert("Test");
}
And want to "invoke" or "call" it via its name.
This is what i tried at least.
$(document).ready(function() {
var fn = window["namespace.showFilter"];
fn();
});
I get error TypeError: fn is not a function
Here is a fiddle http://jsfiddle.net/xBCes/1/
You can call it in the following way:
$(document).ready(function() {
window["namespace"]["showFilter"]();
});
or
$(document).ready(function() {
window["namespace"].showFilter();
});
or
$(document).ready(function() {
window.namespace.showFilter();
});
I found that I had to manually set it to window.
window.namespace = function() { }
window.namespace.showFilter = function () {
alert("Test");
};
$(document).ready(function() {
var fn = window["namespace"]["showFilter"];
fn();
});
http://jsfiddle.net/xBCes/4/
Like this:
$(function() {
window.namespace.showFilter();
});
P.S. I shortened the $(document).ready(...)
function namespace() {}
namespace.showFilter = function () {
alert("Test");
}
$(document).ready(function() {
var fn = namespace.showFilter();
fn();
});
http://jsfiddle.net/xBCes/3/

Function becomes undefined after first trigger

I have a block of code like so:
function doSomething() {
someVar.on("event_name", function() {
$('#elementId').click(function(e) {
doSomething();
});
});
}
// and on document ready
$(function () {
$('#anotherElemId').click(function () {
doSomething();
});
});
The problem that I'm encountering is that when I call doSomething() from anotherElemId click event(that is binded on document ready) it works as expected, but calling it recursively from elementId click doesn't work.
Any ideas? Thinking is something trivial that I'm missing.
Is someVar an actual jQuery reference to a dom element? (e.g. $('#someitem'))
The second problem is you cant put a .click event inside a function that you would like to instantiate later on. If you are trying to only allow #elementId to have a click event AFTER some previous event, try testing if a tester variable is true:
var activated = false;
$(function () {
$('#anotherElemId').click(function () {
activated = true;
});
$('#secondElemId').on("event_name", function() {
if (activated) {
// code that happens only after #anotherElemId was clicked.
}
});
});

How to call javascript function with parameter in jquery event handler?

I am stuck. Searched and tried for hours.
EDIT:
I still can't make it work. Okay, I'll just put the source code to make it clear what I want to accomplish.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
var date_fmt="yyyy-mm-dd";
var time_fmt="HH:MM";
var date_field="#id_start_0, #id_end_0"; //id refering to html input type='text'
var time_field="#id_start_1, #id_end_1"; //id refereing to html input type='text'
function clearFmt(fmt_type)
{
if($(this).val() == fmt_type) {
$(this).val("");
}
}
function putFmt(fmt_type)
{
if($(this).val() == "") {
$(this).val(fmt_type);
}
}
$(document).ready(function() {
$(date_field).attr("title",date_fmt);
$(time_field).attr("title",time_fmt);
$(date_field).click(function() {
clearFmt(date_fmt);
});
$(date_field).blur(function(){
putFmt(date_fmt);
});
$(time_field).click(function(){
clearFmt(time_fmt);
});
$(time_field).blur(function(){
putFmt(time_fmt);
});
});
</script>
Help ?
Use the jquery bind method:
function myfunc(param) {
alert(param.data.key);
}
$(document).ready( function() {
$("#foo").bind('click', { key: 'value' }, myfunc);
});
Also see my jsfiddle.
=== UPDATE ===
since jquery 1.4.3 you also can use:
function myfunc(param) {
alert(param.data.key);
}
$(document).ready( function() {
$("#foo").click({ key: 'value' }, myfunc);
});
Also see my second jsfiddle.
=== UPDATE 2 ===
Each function has his own this. After calling clearFmt in this function this is no longer the clicked element. I have two similar solutions:
In your functions add a parameter called e.g. element and replace $(this) with element.
function clearFmt(element, fmt_type) {
if (element.val() == fmt_type) {
element.val("");
}
}
Calling the function you have to add the parameter $(this).
$(date_field).click(function() {
clearFmt($(this), date_fmt);
});
Also see my third jsfiddle.
-=-
An alternative:
function clearFmt(o) {
if ($(o.currentTarget).val() == o.data.fmt_type) {
$(o.currentTarget).val("");
}
}
$(date_field).click({fmt_type: date_fmt}, clearFmt);
Also see my fourth jsfiddle.
The following should work as seen in this live demo:
function myfunc(bar) {
alert(bar);
}
$(function() {
$("#foo").click( function() {
myfunc("value");
});
});
anyFunctionName = (function()
{
function yourFunctionName1()
{
//your code here
}
function yourFunctionName2(parameter1, param2)
{
//your code here
}
return
{
yourFunctionName1:yourFunctionName1,
yourFunctionName2:yourFunctionName2
}
})();
$document.ready(function()
{
anyFunctionName.yourFunctionName1();
anyFunctionName.yourFunctionName2();
});
Note: if you don't use 'anyFuctionName' to declare any function then no need return method. just write your function simply like, yourFunctionName1().
in $document.ready section parameter is not issue. you just put your function name here. if you use 'anyFuctionName' function then you have to follow above format.
function myfunc(e) {
alert(e.data.bar); //this is set to "value"
}
$("#foo").click({bar: "value"}, myfunc);
People are making this complicated, simply call directly as you would in Javascript
myfunc("value");

Categories

Resources