I am trying to parse $(this) to a function called by another function but without much luck. Essentially my question is; is it possible and if so, how?
Code is as follows:
Initial Call
$('.playform').on('click', playForm);
Primary Function
function playForm(e){
...snip...
TweenLite.to($('.video'), 1, {css:{'height':win.h+'px'}, ease:Power4.easeInOut, onComplete:showForm});
...snip...
}
Secondary Function
function showForm{
$('.video #youtube').append('<iframe class="show-form" src="'+$('.playform').attr('href')+'"></iframe>');
}
As I am going to be using more than one form, I wanted to automate this process but I cant seem to
Things I have tried so far but to no avail
Declared $(this) as a variable
Tried to give the functions parameters
Step 1
$('.playform').on('click', function(){
var whichVid = $(this);
playForm(whichVid);
});
Step 2
function playForm(e){
TweenLite.to($('.video'), 1, {css:{'height':win.h+'px'}, ease:Power4.easeInOut, onComplete:showForm(e)});
}
Step 3
function showForm(e){
$('.video #youtube').append('<iframe class="show-form" src="'+e.attr('href')+'"></iframe>');
}
Alternatively you could establish a global variable before step 1 and then set the value on the click event like
var window.whichVid = '';
$('.playform').on('click', function(){
window.whichVid = $(this);
playForm();
});
function playForm(){
TweenLite.to($('.video'), 1, {css:{'height':win.h+'px'}, ease:Power4.easeInOut, onComplete:showForm()});
}
function showForm(){
var thisVid = whichVid.attr('href');
$('.video #youtube').append('<iframe class="show-form" src="'+ thisVid +'"></iframe>');
}
you could put it like this (not tested) :
(function($){
var global_this;
function palyform(e){
global_this = $(this)
...
}
function showform(e){
// do shomething with global_this
...
}
$('.playform').on('click', playForm);
}(jQuery);
Related
I have two scripts, first of them clicks on the button and after that browser opens a new window, where i should click on the other button by the second script, is it possible to run them both at the same time, I mean like unite those scripts together?
function run() {
var confirmBtn = document.querySelector(".selector,anotherSelector ");
}
after this new window appears and here`s the second part of my script
var rooms = document.querySelectorAll(" .btn-a-offers");
console.log(rooms);
for (var room = 0; room < rooms.length; room++) {
rooms[room].click();
}
var prices = document.querySelectorAll(" .li-right-side>strong");
console.log(prices);
for (var price = 0; price < price.length; price++) {
}
var prices = [];
document.querySelectorAll(".new-pa-hotelsoffers .li-right-side > strong").forEach(function(price) {
prices.push(parseFloat(price.innerHTML.replace(/[^0-9.]/g, "")))
})
console.log(
Math.min(...prices).toFixed(2)
)
My English is not that good so I want to be sure that I explained everything right, second script must be executed in the new window, that opens after first script
Depending on the logical dependancy of your application and the use of the functions, you could execute the second function in a document.ready function on the second page.
Example:
<script>
//jQuery
$( document ).ready(function() {
secondFunction();
});
//Pure JS
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
r(function() {
secondFunction();
});
</script>
However, if the page is to act independantly, and the second function is only to respond upon the execution of the first function, then that solution would not be the one you are looking for.
In the case where the function has to act entirely dependant on the use of the first function you could parse a value in the URL (better known as a GET variable) and check if that value is set.
Example:
<script>
functionOne() {
window.location.href = '/your_page.php?click=1';
}
</script>
Then on your second page you need to retrieve the GET variable.
<?php
$clicked = $_GET['click'];
?>
You can then perform a check to see if the variable has been set and fire your function upon that logic.
<?php
if($clicked != "") {
echo '
<script>
functionTwo();
</script>';
}
?>
Another way of doing it could be by the use of AJAX and have the other function execute in the AJAX' success function. That way you can eliminate the use of the GET variable, which is visible in the URL.
Example:
<script>
functionOne() {
$.ajax({
type : "POST", //or GET
url : "/your_page.php",
data : {
//parse your POST variable data if any
// variable : value,
// anotherVairable : anotherValue
// [....]
},
success: function (html) {
//Success handling
secondFunction();
}
})
}
</script>
Note that the AJAX used in the example is jQuery AJAX, so if you want to use some AJAX logic involving this structure, you'll need to include a jQuery library.
You should pass some parameter in the URL query like this:
// first-script.js
openNewWindow('http://example.com?run-second-script=1') // openNewWindow is fake function, just for demo
// second-script.js
if (window.location.search.includes('run-second-script=1')) { ... your code here ...}
<div id='example' data-fn='functiona'>OK</div>
$('#button').click function(){
$('#example').attr('data-fn', functionb');
});
function functiona(){
console.log('functiona');
}
function functionb(){
console.log('functionb');
}
$('#example').click(function(){
// execute function currently stored inside data-fn attribute
});
Probably everything is clear.
I need dinamically change the function which will be executed by clicking on example.
The current function should be stored inside data-fn.
Any help?
What you want to do is described in Can you set a javascript function name as an html attribute?
But I suggest that you solve it that way:
$('#button').click(function() {
$('#example').off('click.myNamespace') // remove the previously assigned callback
.on('click.myNamespace', creatClickCallback(functionb)); // register the new callback
});
function functiona() {
console.log('functiona');
}
function functionb() {
console.log('functionb');
}
function creatClickCallback(functionToCall) {
return function(evt) {
functionToCall()
}
}
$('#example').on('click.myNamespace', creatClickCallback(functiona));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='example'>OK</div>
<div id='button'>button</div>
This way you ensure that you do not accitantily name a function the wrong way, because you pass it as an actual reference to that function instead of a string.
Couldn't you just store the function name, then when you click you check which function is then call it and update the function to which one you want?
Something like this:
function functiona(){
console.log('called functiona');
document.body.style.background = '#aaa';
}
function functionb(){
console.log('called functionb');
document.body.style.background = '#fff';
}
$('#example').on("click", function(ev){
var func = $(ev.target).attr('data-fn');
console.log(func);
window[func]();
});
$('#changer').on("click", function(ev){
//HERE you can change the function will be called based on what you want
//Here I just changed it with a simple if...
var fn = $("#example").attr("data-fn");
if (fn == 'functiona'){
$("#example").attr("data-fn", "functionb");
}else {
$("#example").attr("data-fn", "functiona");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='example' data-fn='functiona'>Click Me to call function</div>
<button id='changer'>Change Function</button>
Here, the global variable window have your functions stored, so going through it by it's name and calling it, should work, if this name exist as a function window[stringOfFuncionName]();
This is not the best way of doing what you need (actually you didn't let completely clear your final objective), but this maybe can help.
I have a function fillOpenOrders that I call via require. The function is then supposed to be called in $(document).ready() along with some other functions. The problem is that fillOpenOrders does not get called. It is ignored and other functions are executed normally.
I have a DataTable with Id of "mainTable. When i click on any row, the following code should be executed.
var functions = require("./functions");
var openOrdersT = require("./src/openOrders");
$(document).ready(function () {
$('#mainTable tr').on('click', function () {
var id = $(this).find('td:first').text();
document.getElementById("coin-name").innerHTML = id;
openOrdersT.fillOpenOrders();
functions.fillNavPrices();
widget.onChartReady(function () {
var chart = widget.activeChart();
chart.setSymbol(id);
});
});
});
Other functions (fillNavPrices etc.) are working normally.
What am I doing wrong?
Update
The code for openOrdersT looks like this.
module.exports{
fetchOO: function(){...},
fillOpenOrders: function(){
//It doesn't matter what is inside here. I tried with a simple alert or console.log function here.
//Function is meant to update a DataTable with new data.
}
}
Meanwhile fetchOO() works like expected.
i try to pass paramater to function. When i click the div it will alert the paramater that i pass
i have 2 file
index.html
script.js
here's what i try
Example 1
index.html
<div id="thediv" >
script.js
window.onload = initialize;
//bind event listener
function initialize(){
document.getElementById("thediv").onclick = myFunction(" something ");
}
//end of bind
//function
function myFunction(parameter) { alert( parameter ) };
//end of all function
the trouble is the function its executed without click
Example 2
index.html
<div id="thediv" onclick="myfunction('something')" >
script.js
function myFunction(parameter) { alert( parameter ) };
yap its done with this but the trouble if i have many element in index.html it will painful to read which element have which listener
i want to separate my code into 3 section (similiar with example1)
the view(html element)
the element have which listener
the function
what should i do? or can i do this?
(i don't want to use another library)
Placing () (with any number of arguments in it) will call a function. The return value (undefined in this case) will then be assigned as the event handler.
If you want to assign a function, then you need to pass the function itself.
...onclick = myFunction;
If you want to give it arguments when it is called, then the easiest way is to create a new function and assign that.
...onclick = function () {
myFunction("arguments");
};
Your first solution logic is absolutely ok .. just need to assign a delegate ... what you are doing is calling the function .. So do something like this ...
//bind event listener
function initialize(){
document.getElementById("thediv").onclick = function () { myFunction(" something "); };
}
//end of bind
Instead of assign you invoke a function with myFunction();
Use it like this
//bind event listener
function initialize(){
document.getElementById("thediv").onclick = function(){
myFunction(" something ");
}
}
I have functions in side a document.ready and I want to call them using value inside a variable.. I tried to use window[variablename](); but it is not working inside document.ready but when called it directly it works..
think this is the function inside the document.ready
$(document).ready(function() {
function jhon(){
alert('works');
};
});
I'm getting function name from a variable,value of that variable is the name of the function..
below code will get the URL's hashed part example: #JHON and remove # and store it inside URLHASH variable..example: JHON
var urlhash = document.location.hash;
urlhash = urlhash.replace(/^.*#/, '');
when I called like this it is not working..
window.onload=function() {
window[urlhash]();
};
but when I call the function like this it is working fine..
window.onload=function() {
jhon();
};
Is it possible to call a function using variable value?
This:
window.onload=function() {
window[urlhashed]();
};
Contains a typo: urlhashed ought to be urlhash
window.onload=function() {
window[urlhash]();
};
In addition to that you have defined jhon() inside of another function, which capture's it in that enclosing functions scope.
if you want to have this work as intended you ought to change this:
$(document).ready(function() {
function jhon(){
alert('works');
};
});
to be more like this:
$(document).ready(function() {
window.jhon = function(){
alert('works');
};
});
Define the function jhon outside of $(document).ready. Otherwise, it'll be hidden, and thus inaccessible via window[function_name]:
function jhon(){
alert('works');
};
$(document).ready(function() {
var urlhash = document.location.hash;
urlhash = urlhash.replace(/^.*#/, '');
window[urlhash]();
});