jQuery function calling twice - javascript

I've got this jquery code, and once I call it the first part of the function initiates, but then right after that the second part initiates; it's like the if statement isn't working. Have i got any problems with my code?
$(".pinPane").click(function()
{
if ($('.pinPane').hasClass('open'))
{
var htable = $('#content-panel-content').height();
var wtable = $('#content-panel-content').width();
var panew = wtable - 2;
var paneh = htable * 0.7;
var tableh = htable * 0.3;
$('.pane')
.height(paneh)
.width(panew)
.addClass('panepinned')
.removeClass('shadow');
$('#content-panel-content').height(tableh);
$('.pinPane').addClass('cls').removeClass('open');
}
else
{
$('#content-panel-content').css('height', '100%');
$('.pane').css('height', '100%').css('height', '-=200px');
$('.pane').css('width', '100%').css('width', '-=40px');
};
});

instead of:
$('.pinPane').addClass('cls').removeClass('open');
use:
$(this).addClass('cls').removeClass('open');
as in first case it will remove class from all elements with class pinpane. once u removed class then else code will be executed as now its not contain the open class.
if its calling twice then it can be case of event propagation. You can stop it by:
$(".pinPane").click(function(event)
{
event.stopPropagation();
//rest of your code
}

it's like the if statement isn't working
Depending on your needs the following line of code inside your click handler may give unexpected result:
if ($('.pinPane').hasClass('open'))
Basically you check if any .pinPane has a class open; don't you want to only check the .pinPane that raised the click event? If so change it to:
$(".pinPane").click(function()
{
if ($(this).hasClass('open')) { //note this here
} else {
};
});

Related

Ignore function if occurred within x seconds

Since people are misunderstanding my wording, I will rewrite it, I want "with the following code below" to ignore the function which i have commented on below in my jquery if it happened in the last "X" seconds.
Here is my code.
EDIT:: Please write answers in reference to this, example. "the script ignores the change in class and the delay wont work" http://www.w3schools.com/code/tryit.asp?filename=FBC4LK96GO6H
Sorry for confusing everyone including myself.
Edited due to author's post update.
You can create custon event. By this function you will define: "delayedClick" event on the selected objects.
function delayedClickable(selector, delayTime){
$(document).ready(function(){
$(selector).each(function () {
var lastTimeFired = 0;
$(this).click(function(){
if(Date.now() - delayTime > lastTimeFired) {
lastTimeFired = Date.now();
$(this).trigger('delayedClick');
}
});
});
});
}
Remeber that you should define delayTime and this event on selected elements by:
var delayTime = 3 * 1000; // 3 sec delay between firing action
delayedClickable('.Img2', delayTime);
And then just use your event on elements. For example click event can be used in that way:
$element.on('click', function () {
// ...
});
And your custom delayedClick event should be used in that way:
$element.on('delayedEvent', function () {
// ...
});
Full example:
http://www.w3schools.com/code/tryit.asp?filename=FBC56VJ9JCA5
#UPDATE
I've found some another tricky way to keep using click function and makes it works as expected:
function delayedClickable(selector, delayTime){
$(document).ready(function(){
$(selector).each(function () {
var scope = this;
$(this).click(function(){
scope.style.pointerEvents = 'none';
setTimeout(function () {
scope.style.pointerEvents = 'auto';
}, delayTime);
});
});
});
}
And then
var delayTime = 3 * 1000; // 3 sec delay between firing action
delayedClickable('.Img2', delayTime);
That's all.
The key of second way is that we are disabling any pointer event on element when clicked and then after timeout we're turning these events back to work.
https://developer.mozilla.org/en/docs/Web/CSS/pointer-events
And full example:
http://www.w3schools.com/code/tryit.asp?filename=FBC678H21H5F
Can use setTimeout() to change a flag variable and a conditional to check flag in the event handler
var allowClick = true,
delaySeconds = 5;
$(".element1").click(function(){
if(!allowClick){
return; // do nothing and don't proceed
}
allowClick = false;
setTimeout(function(){
allowClick = true;
}, delaySeconds * 1000 );
// other element operations
})

How can I modify an anonymous javascript function with tampermonkey?

Here is the block of code I want to replace:
$(document).ready(function () {
$(".button-purple").click(function () {
interval = $(this).attr('id');
name = $(this.attr('name');
if(Number($(this).val()) === 0) {
if(name == 'static') {
do this
}
else {
do this
}
}
else {
do this
}
});
});
I can't find any documentation on trying to replace the function since it's unnamed though. Is it possible to replace the entire javascript file + delete the line loading it / insert my own script? Would really appreciate any help I can get.
If you just want to remove the click event handler, then simply say
var $element = $(".button-purple");
$element.off('click');
If you want to Remove all the event handlers, then you'll first have to find out what all event handlers are present and then remove them iteratively.
var element = $element[0]; //Make sure the element is a DOM object and not jQuery Object.
// Use this line if you're using jQuery 1.8+
var attachedEvents = $._data(element,'events');
// Use this line if you're using jQuery < 1.8
var attachedEvents = $(element).data('events'); //Here you can also replace $(element) with $element as declared above.
for(var event in attachedEvents){
$element.off(event);
}
UPDATE:
You can simply add your own event handler (using .on() API) after you're done removing all the required existing handlers.
Just define your function.
function yourFunction(){ /* your code */};
$element.on('click', yourFunction);
Update 2:
Since you just want to remove the click event handler, this is the simplest code that will serve your purpose.
$(".button-purple").off('click').on('click', yourFunction);
I'm not aware of tampermonkey, but you can try this:
function chickHandler() {
interval = $(this).attr('id');
name = $(this.attr('name');
if (Number($(this).val()) === 0) {
if (name == 'static') {
do this
} else {
do this
}
} else {
do this
}
}
}
function onReadyHandler() {
$(".button-purple").click(chickHandler);
}
$(document).ready(onReadyHandler);
When you do something like .click(function(){...}), here function is called as a callback. You have to send a function as a callback. Not necessary to be anonymous.

Passing parameters to a event listener function in javascript

Hello I have some code in which I take user input through in html and assign it to,two global variables
var spursscoref = document.getElementById("spursscore").value;
var livscoref = document.getElementById("livscore").value;
Which next show up in this addeventlistener function as parameters of the whowon function
var d = document.querySelector("#gut2");
d.addEventListener("click", function () {
whowon(spursscoref, livscoref, spurs, liverpool)
}, false);
The click event is meant to trigger the whowon function and pass in the parameters
function whowon(FirstScore, SecondScore, FirstTeam, SecondTeam) {
if (FirstScore > SecondScore) {
FirstTeam.win();
SecondTeam.lose();
} else if (FirstScore < SecondScore) {
SecondTeam.win();
} else {
FirstTeam.draw();
SecondTeam.draw();
}
}
However the values are null,as I get a cannot read properties of null error on this line
var spursscoref = document.getElementById("spursscore").value;
I am pretty sure the problem is coming from the addlistener function,any help would be appreciated
Well you could do something like this -
$( document ).ready(function() {
var d = document.querySelector("#gut2");
d.addEventListener("click", function () {
var spursscoref = document.getElementById("spursscore").value;
var livscoref = document.getElementById("livscore").value;
whowon(spursscoref, livscoref, spurs, liverpool)
}, false);
});
Wrap your code in $(document).ready(function(){}). This will ensure that all of your DOM elements are loaded prior to executing your Javascript code.
Try putting all of your code inside this
document.addEventListener("DOMContentLoaded", function(event) {
//Your code here
});
My guess is that your code is executed before the html actually finished loading, causing it to return null.

Google Apps Script Find function caller id

I have a Google Apps Script that dynamically generates buttons and assigns for each a ClickHandler which in turn calls a function.
My problem is that because every button calls the same function I can't find a way to indentify which of them actually made the call. Here is a code sample:
var handler = app.createServerHandler("buttonAction");
for (i=1,...) {
app.createButton(...).setId(i).addClickHandler(handler);
}
function buttonAction() {
//How do I know what button made the call?
}
Another option is to use the e.parameter.source value to determine the ID of the element that triggered the serverHandler to be called.
Here's an example:
function doGet(e) {
var app = UiApp.createApplication();
var handler = app.createServerHandler("buttonAction");
for (var i = 0; i < 4; i++) {
app.add(app.createButton('button'+i).setId(i).addClickHandler(handler));
}
return app;
}
function buttonAction(e) {
var app = UiApp.getActiveApplication();
Logger.log(e.parameter.source);
}
e.parameter.source will contain the ID of the element, which you could then use to call app.getElementById(e.parameter.source) ...
You could create multiple handlers, each for one button:
for (i=1,...) {
var handler = app.createServerHandler("buttonAction" + i);
app.createButton(...).setId(i).addClickHandler(handler);
}
function buttonAction1() {
// code to handle button 1
}
function buttonAction2() {
// code to handle button 2
}
function buttonAction...
I wouldn't recommend of having these sort of "anonymous" action handlers though, as you might be having troubles later in remembering which actionX does what.
(e.g. have a different approach, w/o a loop, or prepare a dictionary-like/array object of meaningful handler names before that loop.)
OTOH, you could use event object argument provided to your callback function:
function buttonAction(event) {
// use event object here to identify where this event came from
}
The thing is the above event object properties depends on where your callback is being called from. For instance, if it were a submit button where you had a Form, then you could access parameters submitted by that from like so: event.parameter.myParamName. See code sample here.
So, if you have a variable number of buttons, you could use a hidden element + the button:
for (i=1,...) {
var hiddenAction = app.createHidden("action", "action"+i);
var handler = app.createServerHandler("buttonAction");
handler.addCallbackElement(hiddenAction);
var btn = app.createButton("Button text", handler);
// you'll need to add both btn and hidden field
// to the UI
app.add(hiddenAction);
app.add(btn);
}
Then, your buttonAction might look like this:
function buttonAction(e) {
var action = e.parameter.action;
// do something based on action value here
// which will be one of "action1", "action2", ...
}
The above is a copy & paste from Hidden class sample.
The above might not work out of the box, but you get the idea: create a hidden element that holds the info you need in your callback, and attach that hidden to your server handler. You could even create multiple hidden elements or a Form panel.
I have the same issue. It works using Tag.
EG
SETUP
var button = addButton(app
,panel
,"buttonActiveTrelloProjects_" + i.toString()
,appVars.buttonWidth() + "px"
,appVars.level2ButtonHeight().toString() + "px"
,false
,false
,"Trello"
,"buttonActiveTrelloProjectsHandler"
,(appVars.buttonLhsGap() * buttonCntr) + (appVars.buttonWidth() * (buttonCntr - 1 ) + 9)
,(appVars.level2ButtonTopGap() * 34)
,3
,"button");
button.setTag(projectName );
USE
function buttonActiveProjectsChartHandler_1(button){
...
buttonTag = getButtonTag(button);
chartType = buttonTag.split(";")[1];
activeProject = buttonTag.split(";")[0];
...
}
function getButtonTag(button){
var jsonButton = JSON.stringify(button);
var source = button.parameter.source;
var tagPtr = source + "_tag";
return button.parameter[tagPtr];
}

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

Categories

Resources