Keeping variables between function executions (Javascript) - javascript

I have a JavaScript function that runs every time one of the many links is clicked. The functions first checks what the id of the link clicked is, then it runs an if stement. depending on the id of the link, different variables are defined.
All this works, but the problem is that some links define one variable while other links define another, I need to keep the variables defined in previous executions of the function defined for other executions of the function.
An example follows:
$(document).ready(function()
{
$(".sidebar a").click(function(event) {
event.preventDefault()
var targetID = $(this).attr("data-target")
$("#" + targetID).attr("src", $(this).attr("href"))
var element = $(this).attr("class")
if (element == "submit") {
var submit = $(this).attr("user")
alert("1")
} else if (element == "view") {
var view = $(this).attr("user")
alert("2")
}
})
window.history.replaceState({}, 'logs', '/file/path?submit=' + submit + '&' + 'view=' + view)
})
Thanks

You can use an outer function which does nothing but declare some variables and return an inner function. The inner function can access the variables from the outer scope which stay the same for every call of the function.
Example
var next = (function() {
var value = 0;
function next() {
return value++;
}
}());
console.log(next());
console.log(next());
console.log(next());
Live demo
http://jsfiddle.net/bikeshedder/UZKtE/

Define the variables in an outer scope:
$(document).ready(function () {
var submit;
var view;
$(".sidebar a").click(function (event) {
event.preventDefault();
var targetID = $(this).attr("data-target");
$("#" + targetID).attr("src", $(this).attr("href"));
var element = $(this).attr("class")
if (element == 'submit') {
submit = $(this).attr("user")
alert("1")
} else if (element == 'view') {
view = $(this).attr("user")
alert("2")
}
});
});

Create var submit and view outside of the function so it has a global scope.

You can store arbitrary data on a matched element with JQuery's .data() function.
Example:
$(this).data("submit", $(this).attr("user")); // set a value
var submit = $(this).data("submit"); // retrieve a value
This places the data in the context of JQuery's knowledge of the element, so it can be shared between function calls and even between different events.

Related

Change value of first iteration input with next iteration input value

Structure Concept:-
Basically, i am trying to create the modal window containing input and that modal window currently fires when the input on index page get focused for that I have used data attribute to make a link between them by assigning them same attribute value.
Javascript Concept:-
for the modal window, I have created the modal object. and model object contains a bindModal method which takes one argument and that argument is data attribute value. after taking that value bindModal method will search dom elements containing that particular value and after the search, I iterate over them using each loop.
Problem
So basically I want whenever user starts typing on the model input it should get written automatically in input on the index page.
I will appreciate you all if guys help me out to make my code more optimized and well structured and most important thing is that let me know what mistake I have done in overall work Thanks
JavaScript Code
var modal = function () {
this.toggleModal = function () {
$('#modal').toggleClass('content--inActive').promise().done(function () {
$('#modal__close').on('click',function(){
$('#modal').addClass('content--inActive');
});
});
}
this.bindModal = function (bindVal) {
var bindValue = $(document).find('[data-modal-bind = ' + bindVal + ']');
$.each(bindValue, function (index) {
var bind1 = $(this);
if(index === 1) {
var bind2 = $(this);
$(bind1).change(function (){
$(bind2).val(bind1.val());
});
}
});
}
}
var open = new modal();
$('#input_search').on('click',function(){
open.toggleModal();
open.bindModal('input');
});
Here is one way to do what you want:
var modal = function() {
this.bindModal = function(bindVal) {
var bindValue = $('[data-modal-bind = ' + bindVal + ']');
bindValue.each(function(index) {
$(this).keyup(function() {
var value = $(this).val();
bindValue.each(function(i, e) {
$(this).val(value);
});
});
});
}
}
$('#input_search').on('click', function() {
var open = new modal();
open.bindModal('input');
});
Changes done:
I cached the inputs with same binding values in bindValue variable, and then bound the the keyup event for each of them. On keyup, the value of the current input is get in value, which is then assigned to each input using the inner loop.
This makes the inputs to be in sync while typing. Hope that solves your issue.

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.

field value gets undefined jquery

Can I Clear a event que in javascript?
when I have done one click event and then does another click event the input field gets the value undefined even when it has a value like "newfile.jpg"
I retrieves the values by doing somevariable = $('#cke_104_textInput').val();
but somevariable gets the value undefined.
here is the javascript code:
$(function () {
// Handler for .ready() called.
function changeLink() {
link = $('#cke_104_textInput').val();
if (link == "") {}
else {
link = link.replace("_", "/");
parts = link.split('.');
explodeExtension = parts[parts.length - 1];
link = link.replace("/download/", "/download/" + explodeExtension + "/");
link = link.replace("." + explodeExtension, "");
$('#cke_104_textInput').val('');
$('#cke_104_textInput').val(link);
clearInterval(changelink);
}
}
function changePic() {
link = $('#cke_103_textInput').val();
if (link == "") {}
else {
link = link.replace("_", "/");
parts = link.split('.');
explodeExtension = parts[parts.length - 1];
link = link.replace("/download/", "/show/" + explodeExtension + "/");
link = link.replace("." + explodeExtension, "");
$('#cke_103_textInput').val('');
$('#cke_103_textInput').val(link);
clearInterval(changepic);
}
}
$('#cke_60').live('click', function (event) {
changelink = setInterval(function () {
changeLink()
}, 1000);
});
$('#cke_64').live('click', function (event) {
changepic = setInterval(function () {
changePic()
}, 1000);
});
});
In the code i try to rewrite the content of two input fields.
this has to be done because the files are not in the sites root they are outside of it, and to be able to show or download them on the site the urls need to be in a specific format.
To answer your first line question, yes you can. Take a look at unbind()
You are creating link as a global variable, which means it is clashing with itself.
Change link = $('#cke_104_textInput').val(); to var link = $('#cke_104_textInput').val();.
Also as a side note, you have this code twice:
$('#cke_104_textInput').val('');
$('#cke_104_textInput').val(link);
which is redundant and inefficient. You should remove the first line in both cases, because selecting an element (even via ID) is not a free operation.

setInterval / clearInterval Issue inside it's scope

I have the following code, and it works fine until i hit the the #play button. I'm assuming it's because the var intID is set in another place and it's not in the same scope when i window.clearInterval() it... how do I fix this? BTW, this is the Google Maps API Version 3
function intervalTrigger(){
return window.setInterval(function(){
placement++;
if(placement >= markers.length){placement = 0;}
google.maps.event.trigger(markers[placement], "click");
}, 5000);
};
var intID = intervalTrigger();
$('#map_canvas').click(function(){window.clearInterval(intID);});
$('a[href=#nextmarker]').live('click',function(){
placement++;
if(placement >= markers.length){placement = 0};
google.maps.event.trigger(markers[placement], "click");
window.clearInterval(intID);
$('a[href=#pause]').replaceWith('Play');
return false;
});
$('a[href=#prevmarker]').live('click',function(){
placement--;
if(placement == -1){placement = markers.length-1}
google.maps.event.trigger(markers[placement], "click");
window.clearInterval(intID);
$('a[href=#pause]').replaceWith('Play');
return false;
});
$('a[href=#play]').live('click',function(){
$('a[href=#play]').replaceWith('Pause');
var intID = intervalTrigger();
return false;
});
$('a[href=#pause]').live('click',function(){
window.clearInterval(intID);
$('a[href=#pause]').replaceWith('Play');
return false;
});
Remove the var from your #play click handler to the following:
$('a[href=#play]').live('click',function(){
$('a[href=#play]').replaceWith('Pause');
intID = intervalTrigger();
return false;
});
That will correctly set the value of the global var intID so it's available to the other event handlers.
You're creating a new variable with that var keyword, if you want to reference the variable in the outer scope, you need to take it out, like this:
$('a[href=#play]').live('click',function(){
$('a[href=#play]').replaceWith('Pause');
intID = intervalTrigger();
return false;
});
Otherwise it's just creating a new variable inside that .live() handler that doesn't go anywhere...but since you want to set the variable you already have, leave off the var.

Categories

Resources