Use a parameter value in a callback function - javascript

I'm having issues getting a 'touchmove' event to fire using a parameter value in the callback function. I have success if I pass an "alert" but not a function. Basic concept in the example is the text box goes up by "1" (obj.number) on the 'touchmove' when it's scrolled within the selected div (ID="myDIV").
Here is an example:
function myFunction(num) {
document.getElementById("divText").innerHTML = x += num;
}
function Scroller(area, obj) {
$divarea = document.getElementById(area);
$divarea.addEventListener("touchstart", function() {
obj.alertMe(obj.number); // THIS WORKS
});
$divarea.addEventListener("touchmove", function() {
obj.scrollMe(obj.number) // THIS DOES NOT WORK AND WHAT I NEED TO RUN, "obj.number" SHOULD BE 1
});
var x = 0;
}
$scroll = new Scroller("myDIV", {
number: 1,
alertMe: function(numberValue) {
alert(numberValue)
},
scrollMe: function(numberValue) {
myFunction(numberValue)
}
})
The body is just basic HTML:
<div id="myDIV" >
<!-- a bunch of text goes here so that it scrolls -->
</div>
<div id="divText" ></div>
Would greatly appreciate the overflow community in helping me spot my bug as I have put too much time already into what I know (hope) is going to be a simple solution.
Thanks!

Initialize x as a global variable and that will solve your issue
function Scroller(area, obj) {
$divarea = document.getElementById(area);
$divarea.addEventListener("touchstart", function() {
obj.alertMe(obj.number); // THIS WORKS
});
$divarea.addEventListener("touchmove", function() {
obj.scrollMe(obj.number) // THIS DOES NOT WORK AND WHAT I NEED TO RUN, "obj.number" SHOULD BE 1
});
x = 0;
}

Related

Trigger addEventListener on live element that is not in the DOM (native JavaScript)

I'm stuck with my modal popup plugin since a week.
I'll try to explain as much as i can but first, here is the jsfiddle: http://jsfiddle.net/hideo/yth37hhf/27/
I know the code contains some other functions but they are useful for my plugin.
So, my issue is that the function "triggerLinkAction" contains an addEventListener which is not fired.
(function() {
Window.prototype.triggerLinkAction = function(){
var triggeredLink = document.getElementById("triggeredOtherAction");
var inputTarget = document.getElementById("inputText");
console.log('triggeredLink',triggeredLink);
triggeredLink.addEventListener("click", function (e) {
alert('If this pops out, I will be very happy!!!');
e.preventDefault();
inputTarget.value = "This text should be on the input field...";
}, true);
}
})();
The targeted element is inside the modal, and this modal is displayed by clicking on the link "A small modal".
When the plugin calls ShowModal(), I trigger the TransitionEnd event to call a function
[.... code ...]
function ShowModal() {
vars.popupContainer.classList.add("show");
hsdk.PrefixedEvent(vars.popupOverlay, "TransitionEnd", function (e) {
executeFunctions();
});
}
[.... code ...]
The executeFunctions() will check which functions need to be called:
[.... code ...]
function executeFunctions() {
if (vars.opts && vars.opts.fn) {
var allFunctions = vars.opts.fn.split(',');
for (var i = 0; i < allFunctions.length; i++)
{
var functionName = allFunctions[i];
var functionToExecute = window[functionName];
if(typeof functionToExecute === 'function') {
functionToExecute();
}
}
}
}
[.... code ...]
There are some comments on the javascript part about the plugin, but feel free to ask if I can provide any other information.
PS: I don't care about IE for now ;-)

Stop function after certain number of clicks on a certain element

OK so I am making a reaction tester, and I have a function that makes shapes appear on screen, So what I want is some sort of function were after 5 clicks on a certain element it will end a function. Is there a way of doing that? sorry if its a dumb question, its because I am new to the whole coding...
Here you go
var clickHandler = (function (e) {
var count = 0;
return function () {
count += 1;
if (count > 5) {
return;
}
// do other stuff here
}
}());
aDiv.addEventListener('click', clickHandler, false);
You Can use static variable to count how many times the object has been clicked.
and here is how you can create static variable in javascript.
You can unbind the click event once the counter reaches 5. See the example below
function test(sender) {
sender.dataset.clicked++;
console.log("I've been clicked", sender.dataset.clicked);
if (+sender.dataset.clicked === 5) {
// unbind the event
sender.onclick = null;
}
return;
}
<div onclick="test(this);" data-clicked="0">click me</div>
You may use global variable which may remain counting on click function
<script>
var globalvar = 0;
onclickfunct()
{
globalvar += 1;
if(globalvar == 5)
{
//do my work
}
else
{
//give alert
}
}
</script>

JQuery prototype not working when traversing

I am using the following (http://jsfiddle.net/mkmurray/drv5w/27/) code to allow me to override the .show() function of a DIV.
<script>
(function ($) {
var _oldShow = $.fn.show;
$.fn.show = function (/*speed, easing, callback*/) {
var argsArray = Array.prototype.slice.call(arguments),
duration = argsArray[0],
easing,
callback,
callbackArgIndex;
// jQuery recursively calls show sometimes; we shouldn't
// handle such situations. Pass it to original show method.
if (!this.selector) {
_oldShow.apply(this, argsArray);
return this;
}
if (argsArray.length === 2) {
if ($.isFunction(argsArray[1])) {
callback = argsArray[1];
callbackArgIndex = 1;
} else {
easing = argsArray[1];
}
} else if (argsArray.length === 3) {
easing = argsArray[1];
callback = argsArray[2];
callbackArgIndex = 2;
}
return $(this).each(function () {
var obj = $(this),
oldCallback = callback,
newCallback = function () {
if ($.isFunction(oldCallback)) {
oldCallback.apply(obj);
}
obj.trigger('afterShow');
};
if (callback) {
argsArray[callbackArgIndex] = newCallback;
} else {
argsArray.push(newCallback);
}
obj.trigger('beforeShow');
_oldShow.apply(obj, argsArray);
});
};
})(jQuery);
</script>
I have the following HTML code
<div id="divBeforeHiddenDiv">
foo
</div>
<div id="hiddenDiv" style="display:none">
bar
</div>
And then:
<script>
$('#hiddendiv').bind("beforeShow", function () {
alert("show event successfully overridden");
});
</script>
It works great when I call $('#hiddenDiv').show() but not if I call $('#divBeforeHiddenDiv').next().show() the hidden div containing 'bar' shows but the alert is not displayed.
So why?
UPDATE
This appears to be a jQuery issue as per Bergi's comment. If I use this JSFiddle on jQuery 1.7.1 it works but using jQuery 1.10.1 or any higher version it does not: JSFiddle. Is there a better solution than simply downgrading?
You need to bind the events to the proper elements.
From the example you've given, and what I've interpreted, this piece of code
$('#beforeShow').bind("beforeShow", function () {
alert("show event successfully overridden");
});
Should be
$('#hiddenDiv').bind("beforeShow", function () {
alert("show event successfully overridden");
});
As you want the events to be bound to the hidden div. (or as described in the question, the div right after "#divBeforeHiddenDiv"
You also should change this piece
$('divBeforeHiddenDiv').next().show()
to this
$('#divBeforeHiddenDiv').next().show()
divBeforeHiddenDiv is an ID and in the first code snippet there is no id in the jQuery object.
JSFiddle

Jquery bind not working while within a javascript recursive loop

I am writing a piece of code that changes some lights on a screen from red to green randomly and waits for the user to hit the key that corresponds to the light lit.
When I run this code you are able to hit the a,d,j or l key and an alert will pop up. However, as soon as I click the start button no keys are recognised. And when the loop has finished the bind still seems to become disabled. I have tried moving the bind to other places but I have had no joy. Your help is much appreciated.
$( function() {
$('#start').bind('click', function() { main(); });
$(document).bind('keypress', function(e) { keyPress(e); } );
} );
function getRand(val) {
return Math.floor(Math.random()*val)+1;
}
function main() {
preD = new Date;
preDs = preD.getTime();
randTime=Math.floor(Math.random()*1001)+1500;
playSound();
flash();
}
function flash() {
zone = getZone();
setTimeout(function() {
$('#r'+zone).css("background-image", "url(images/rea_grn.jpg)");
setTimeout(function() {
$('#r'+zone).css("background-image", "url(images/rea_red.jpg)");
if(cond[1] < 8) {
main();
}
} , 200);
} , randTime);
}
function getZone() {
if(condition==1) {
zone = getRand(2);
if( test[1][zone] < 8 ) {
test[1][zone] += 1;
cond[1] += 1;
return zone;
} else {
getZone();
}
}
}
function keyPress(e) {
var evtobj=window.event? event : e //distinguish between IE's explicit event object (window.event) and Firefox's implicit.
var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode
var actualkey=String.fromCharCode(unicode)
if (actualkey=="a" || actualkey=="d" || actualkey=="j" || actualkey=="l" ) {
dd = new Date;
reat = dd.getTime();
alert(1);
//keypressed[condition][zone]['k']=actualkey;
//keypressed[condition][zone]['t']=(reat-preDs);
}
}
The reason that this could be happening is, when you generate code dynamically or alter any existing code the bind needs to be done again, because the function to bind just runs once and only for the members already created. So when you create dynamically code, you are forced to run the binding function to recognize the new elements.
this ways is not very recommended, instead of this, you could bind a container like 'div' or something and inside of this validate which element is calling you. This will work because your container is created once and the binding is properly assigned and doesn't matter if the content of your container changes, the binding always work.
Regards
Using a jquery sound plugin was the answer.
Fixed it with this : plugins.jquery.com/project/sound_plugin

How do I make a function to run only when the mouse is NOT hovering a specified div?

what I got now is:
function()
{
setInterval("getSearch()",10000);
getSearch();
}
);
But I want this interval to pause if the mouse cursor is placed inside a div on my website. How do I attack this problem? Surely I need to give the div an ID.. But some input on how to make the javascript/jquery part is much appreciated.
EDIT: More of my code.. I'm not quite sure where to insert the code in the answers inside this:
$(
function()
{
setInterval("getSearch()",10000);
getSearch();
}
);
TwitterCache = {};
function getSearch()
{
var url = "http://search.twitter.com/search.json?q=test&refresh=6000&callback=?"; // Change your query here
$.getJSON
(
url,
function(data)
{
if( data.results ) // Checks to see if you have any new tweets
{
var i = -1, result, HTML='', HTML2='';
while( (result = data.results[++i]) && !TwitterCache[result.id] )
{
insert html.. blabla}
setInterval returns a "reference" to that interval you set up, allowing you to stop it with window.clearInterval(), and that's what you have to do:
var myInterval;
function startMyInterval() {
if (!myInterval) {
// It's better to call setInterval width a function reference, than a string,
// also always use "window", in case you are not in its scope.
myInterval = window.setInterval(getSearch, 10000);
}
}
function stopMyInterval() {
if (myInterval) {
window.clearInterval(myInterval);
}
}
startMyInterval(); // Start the interval
jQuery("#myDiv").hover(stopMyInterval, startMyInterval);
Set a global variable
var intID;
Assign setInterval to this variable
intID = setInterval("getSearch()",10000);
Set an id for the div
$("#divid").hover(function(){
clearInterval(intID);
},
function(){
// set the interval again
});
I think this should work:
$("#divID").hover(
function () {
PauseTheInterValThing()
},
function()
{
setInterval("getSearch()",10000);
getSearch();
}
);
The simplest way, and the shortest
Simplest method would be:
<div id="yourDiv">
EXAMPLE TEXT
</div>
<script language="Javascript">
var interval = setInterval("getSearch()",1000);
document.getElementById("yourDiv").addEventListener('mouseover', function()
{
clearInterval(interval);
},false);
document.getElementById("yourDiv").addEventListener('mouseout', function()
{
interval = setInterval("getSearch()",1000);
},false);
</script>
insert this in your dom-ready function:
var inv = setInterval("getSearch",1000);
$('#yourdiv').mouseover(function(){
clearInterval(inv);
}).mouseout(function(){
inv = setInterval("getSearch",1000);
})

Categories

Resources