I have an onclick function which performs several tasks. In another JavaScript function I do not have access to the context variables needed to perform these tasks. To get around this I have been simply calling the onclick function directly.
The problem I have now is that I'd like to perform a task after an Ajax action in the onclick completes. Is there any way for me to pass a function to the onclick method of a link? What would the onclick attribute look like?
e.g. something like this:
<a id="link3" href="javascript:void(0);" onclick="function(callback) { X(a); Y(b); Z(c, callback); };">click me</a>
Clicking on this would pass "undefined" as the callback, while I could also call it explicitly like this:
document.getElementById("link3").onclick(function() { alert("Completed all tasks"); } );
Is something like this possible? Basically I want to be able to pass an optional parameter to the onclick method, but if it's absent I want it to behave as if there were just procedural code in the onclick.
EDIT: Added more specifics
The use case is that the onclick calls a search function which requires session variables. When regular searches are performed there is no problem, but when I wish to refresh the search results (e.g. when a the user edits or deletes one of the returned results) I need to call the same search function that was called previously and then print out a feedback message after they are refreshed. This feedback message output is what I would like to be in the callback method. I'd also like to set the window.location.href to page down to the affected row in the event of an edit or an insert.
I have access to several variables on the server side which I print out directly to the onclick attribute when I render the page. In other JavaScript files that I am including on my page I would also like to be able to execute the same functions contained within the onclick. The only problem being that I would have to pass all these variables to those functions indirectly through several intermediate methods in the call chain.
The other option is to print these values to hidden page values and then retrieve them from within my method, but I would like to avoid this as it would be cluttering up everything just so that I could decorate my function call with some visual after-effects.
Although this may be possible somehow, I would recommend not to add arguments to the native DOM events.
I can't see a real architectural need for this, either. Can you make a full example of a use case where you need this? I'm pretty sure someone can come up with an alternative solution that doesn't make additional arguments necessary.
Wouldn't, in your example, the right place to place the alert be the success callback of the Ajax request?
This works for me:
<body onload="f = document.getElementById('link3').onclick; f(function(){alert('Completed all tasks')});">
<input id="link3" type="button" onclick="alert(typeof(arguments[0])); arguments[0]()">
</body>
The first directive returns "function", and the second one returns "Completed all tasks", as expected. In your case, the following should work:
<input id="link3" type="button" onclick="X(a); Y(b); Z(c, arguments[0]);">
Related
I'm trying to call a function on a click event before the href is invoked. I want to do this so that I can set a value to a given variable and then when I redirect to the new page I can access that variable via this.$parent.varName. This is what I'm trying to do but it won't call the function:
<a #click="openWorkflow(rec.id)" href="#/workflows">Edit</a>
Not sure what I'm doing wrong here and/or if this is the right way to achieve what I want
I'd take care of redirecting to the next page inside the openWorkflow function, then you can place it directly wherever you need it to be in the logic. If you're using vue-router, you can do this by just running router.push("#/workflows"). If you're not, you can still do the standard window.location.href = 'baseurl.com/#workflows'.
I am working on a project on Google Apps Script. I have a JS function that returns a date (as a text). I also have an HTML document to display a form with several inputs. I would like to prefill one input with the date returned by the JS funtion. It almost works, except it displays "undefined" instead of the date, even though I know the js funtion is working fine.
Here are some code to better understand :
The input where I call the script (don't mind the onmousemove, i just didn"t find anotherway to call the script).
<input type="text" id="deliveryDate" name="deliveryDate" onmousemove="displayActiveDate()">
So it calls the folowing script.
<script>
function displayActiveDate(){
var activeDate = google.script.run.getActiveDate();
document.getElementById("deliveryDate").value = activeDate;
}
</script>
Which in turn calls getActiveDate() which is the separate JS function that returns the date.
If you have any idea on how to solve this, I will be very thankful.
google.script.run.serverSideFunction() returns undefined. In order to get the actual response value from your serverSideFunction() you need to use the withSuccessHandler() method with a callback like so:
google.script.run.withSuccessHandler(onSuccess).serverSideFunction();
function onSuccess(data) {
// do something with the data returned by the serverSideFunction()
}
Also note that you also have withFailureHandler(err) to handle any errors you server-side functions may return.
Here is the full reference
Instead of writing document.getElementById("deliveryDate").value = activeDate; type document.getElementById("deliveryDate").innerHTML= activeDate; in your script
I'm trying to modify/limit/prevent access to certain JS commands of my browser. For example commands like navigator.clipboard; However, I'm not sure how to approach this.
Is it possible to override these commands with user-defined javascript injected in the page, or do i have to edit the browser's javascript compiler and re-compile it from source for this?
I'm not really familiar with browsers and want to save time by knowing a general direction to follow. Thanks
First of all navigator.clipboard is not a function, but here is an example using the read function of navigator.clipboard:
navigator.clipboard.read = function (originalFunction) {
return function (yourParamsYouWantForThisFunction) {
// Do Stuff you wanna do before the real call. For example:
console.log(yourParamsYouWantForThisFunction);
// Call the original function
return originalFunction.call();
};
}(navigator.clipboard.read); // Pass the original function reference as a parameter
You may wonder, why there are two function statements:
The first one is there, so that we can pass the original function at runtime. If we would not do that, we would not be able to access the original navigator.clipboard.read function.
The second function is the actual function, that you will be using later, when you call navigator.clipboard.read().
I am currently trying to convert a lot of backend code to front end (to lighten the load on a small system).
The code at the moment calls a PHP function to return specific information. (e.g. image locations, strings, styling)
I am converting this code to its js equivalent, the content from Mysql was converted to JSON and stored in a read only file and I am accessing that file using this code:
<script>
function jsread(tag) {
$.getJSON("/strings.json", function(result){
document.write(result[tag]['value']);
});
}
</script>
I want the function to "print" where ever it is invoked. document write writes the value to the page but stops all other loading and write only the value.
Let me be very clear on this: I DO NOT want to use anything that needs extra calls or references out side of this function, that will take months of work so no getting elements by their IDs I have already view many questions on this subject and none are what I can work with. I need something that can be applied to every situation. Other wise I will just have to read the JSON using PHP as a middle compromise.
The problem here is, document.write()'s behaviour is crazy across all the browsers, because, it directly modifies the document object and messes up with the events attached. So it is always better to avoid this function as each browser defines it differently and has a different effect on the same code, with different browsers.
Is there a way to use them without a direct reference?
Solution
The wise thing is, as I said in the comments, it is better to use one of the jQuery functions safely, which create a textNode and insert it the right way, without affecting the others:
<script>
function jsread(tag) {
$.getJSON("/strings.json", function(result){
$("body").append(result[tag]['value']);
});
}
</script>
In case, if you wanna do something like having a placeholder and doing stuff, then you can try giving something like this:
$(function () {
var data = "Dummy Data, that would probably get returned from the getJSON";
// Inside the Success function, do this:
$("span.placeholder-of-the-json").replaceWith(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="placeholder-of-the-json">This gets replaced</span>
So here' s the piece of code. I'm very new to JavaScript so don't be afraid to explain the obvious
$(".my-css-class").on("click", function() {
($(this).attr("data-property-1"), $(this).attr("data-property-2"), this);
});
There's an element in the .jsp page that looks like this:
<i class="clickMe"></i>
I know the .jsp creates a link-icon, and that the above JavaScript is an event handler. I know that it passes these 3 values as arguments another JavaScript method:
function doStuff(prop1, prop2, obj) {
if (prop1 == 'foo') {
//do stuff with prop2
}
else{
// do stuff with obj
}
}
It all works fine. What I want to know is what exactly is going on to make it work? I can't find anything in the code that connects what the event-handler returns to the 'doStuff' java-script function.
The names are totally different, so it's not reflection, it can't be parameter matching because there's other functions with the same number and type of parameters in the file, it can't be convention based because it still works if I find/replace the name of the function to gibberish.
I guess basically I'm asking what this line is doing:
($(this).attr("data-property-1"), $(this).attr("data-property-2"), this);
tl;dr: I'm at a loss, I know how the properties get as far as the onClick event-handler's anonymous function - but how does JavaScript know to pass them as arguments the to the doStuff() function?
the onClick event is a standard event triggered on click of any clickable html element and is automatically raised by the DOM.
You are hooking in to this by listening on any matched ".my-css-class" elements for an onClick Event.
The jquery syntax ".on" has been simplified over time and allows you to hook into any number of events like "submit" - OnSubmit event , or "load" - onLoad Event
Wherever your on("click", myFunction) event hook is picked up, your myFunction will execute.
Looking at your second point...
because it still works if I find/replace the name of the function to gibberish.
The DoStuff function will be found and replaced across all files in your site? or page? or open tabs? , so therefore it must exist somewhere as "doStuff(" or "giberish(".
so when you do a global find/replace, do each one slowly, until you locate it.
Finally, when you do a view source in the browser, this should either explicitly show you the doStuff function, or at the very least give you a clue as to satelite files loaded at runtime, where you can go and investigate.
Use firebug in firefox to debug loaded resources; the ".net tab" to view external loaded resources and the html/javascript they might contain. (for example: your master page might be loading in an embeded resource that contains the doStuff method, becuase of a user or server control reference in that master page)
Also have a look at this:
http://www.developerfusion.com/article/139949/debugging-javascript-with-firebug/
You can step through the javascipt piece by peice until it hits the doStuff method.
Just remember to set at least 1 breakpoint ;-)