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 ");
}
}
Related
<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.
In my HTML, this works
<div id="portfolio1" onclick="changeMainFrame('lib/portfolio1.html')">
to trigger the following function:
function changeMainFrame(srcURL){
var target = document.getElementById("mainFrame");
target.src = srcURL;
}
I want to migrate it to my javascript doc. But this does not work:
document.getElementById("portfolio1").onclick = changeMainFrame("lib/portfolio1.html");
I can not find out how to fix this. Any hints? Cannot find a similar situation anywhere for something so simple yet time consuming.
document.getElementById("portfolio1").onclick = function() {
changeMainFrame("lib/portfolio1.html");
}
You're calling the function changeMainFrame. What you want to do is supply a function wrapper.
document.getElementById("portfolio1").onclick = function() {
changeMainFrame("lib/portfolio1.html");
}
function changeMainFrame(txt) {
alert(txt);
}
<div id="portfolio1">Click Me</div>
You need to assign a function to document.getElementById("portfolio1").onclick which will be called when that element gets clicked. The problem is that instead of assigning a function, you assigned the result of invoking/calling that function. What you can do instead is provide a function in which inside it you call changeMainFrame:
document.getElementById("portfolio1").onclick = function() {
changeMainFrame("lib/portfolio1.html");
};
You need to either use .onclick or the onclick attribute. Both of them require a handler function, and what you were passing was just the result of running your changeMainFrame function (null). Wrapping it in a function() { } yields your expected result.
function changeMainFrame(srcURL){
var target = document.getElementById("mainFrame");
target.src = srcURL;
}
document.getElementById("portfolio1").onclick = function(){changeMainFrame('https://codepen.io')}
<div id="portfolio1">go to codepen.io</div>
<iframe id="mainFrame" src="https://example.com"></iframe>
I would like to disable a certain function from running as an onclick event.
Here, I would like to disable myfunc1, not myfunc2. Actually I want to disable myfunc1 from the whole page, but anyway this is the only thing that I need.
I have no control over the page and I am using userscript or other script injection tools to achieve this.
What I've tried:
Redefining the function after the page has loaded: I've tried adding an event listener to an event DOMContentLoaded with function(){ myfunc1 = function(){}; }
This seems to be working, but in a fast computer with fast internet connection, sometimes it runs before the myfunc1 is defined (in an external js file that is synchronously loaded). Is there any way that I can guarantee that the function will be executed after myfunc1 is defined?
Is there any way that I can 'hijack' the onclick event to remove myfunc1 by its name?
You should use event listeners, and then you would be able to remove one with removeEventListener. If you can't alter the HTML source you will need something dirty like
function myfunc1() {
console.log('myfunc1');
}
function myfunc2() {
console.log('myfunc2');
}
var a = document.querySelector('a[onclick="myfunc1();myfunc2();"]');
a.setAttribute('onclick', 'myfunc2();');
Click me
Or maybe you prefer hijacking the function instead of the event handler:
function myfunc1() {
console.log('myfunc1');
}
function myfunc2() {
console.log('myfunc2');
}
var a = document.querySelector('a[onclick="myfunc1();myfunc2();"]');
var myfunc1_;
a.parentNode.addEventListener('click', function(e) { // Hijack
if(a.contains(e.target)) {
myfunc1_ = window.myfunc1;
window.myfunc1 = function(){};
}
}, true);
a.addEventListener('click', function(e) { // Restore
window.myfunc1 = myfunc1_;
myfunc1_ = undefined;
});
Click me
Another way this could be done is using Jquery and setting the onlick propery on the anchor tag to null. Then you could attach a click function with just myfunc2() attached.
$(document).ready(function () {
$("a").prop("onclick", null);
$("a").click(function(){
myfunc2();
});
});
function myfunc1() {
console.log('1');
}
function myfunc2() {
console.log('2');
}
<a class="test" href="#" onclick="myfunc1();myfunc2();">Example</a>
You can see the codepen here - http://codepen.io/anon/pen/BLBYpO
Perhaps you are into jQuery.
$(document).ready(function(){
var $btn = $('button[onclick*="funcOne()"]');
$btn.each(function(){
var newBtnClickAttr;
var $this = $(this);
var btnClickAttr = $this.attr("onclick");
newBtnClickAttr = btnClickAttr.replace(/funcOne\(\)\;/g, "");
$this.attr("onclick", newBtnClickAttr);
});
});
Where in the variable $btn gets all the button element with an onclick attribute that contains funcOne().
In your case, this would be the function you would like to remove on the attribute e.g., myfunc1();.
Now that you have selected all of the elements with that onclick function.
Loop them and get there current attribute value and remove the function name by replacing it with an empty string.
Now that you have the value which does not contain the function name that you have replace, you can now update the onclick attribute value with the value of newBtnClickAttr.
Check this Sample Fiddle
function bubble(content, triggerElm){
this.element = $('<div class="bubble" />').html(content);
this.element.css(.....) // here is positioned based on triggerElm
}
bubble.prototype.show = function(){
$(document).on('click', this._click.bind(this));
this.element.css(....)
};
bubble.prototype.hide = function(){
$(document).off('click', this._click.bind(this));
this.element.css(....)
};
bubble.prototype._click = function(event){
console.log('click', this);
if(this.element.is(event.target) || (this.element.has(event.target).length > 0))
return true;
this.hide();
};
var b = new bubble();
b.show();
b.hide();
I keep seeing click in the console, so the click does not unbind.
But if I remove the bind() call the click is unbinded. Does anyone know why? I need a way to be able to change "this" inside my test function, that's why I'm using bind().
The problem is that this._click.bind() creates a new function every time it's called. In order to detach a specific event handler, you need to pass in the original function that was used to create the event handler and that's not happening here, so the handler is not removed.
If there are only going to be a few bubbles in your app, you could and simply not use this. That will remove a lot of the confusion about what this is referring to and ensure that each bubble retains a reference to its own click function that can be used to remove the event as needed:
function bubble(content, triggerElm) {
var element = $('<div class="bubble" />').html(content);
element.css(.....); // here is positioned based on triggerElm
function click(event) {
console.log('click', element);
if (element.is(event.target) ||
element.has(event.target).length > 0) {
return true;
}
hide();
}
function show() {
$(document).on('click', click);
element.css(....);
}
function hide() {
$(document).off('click', click);
element.css(....);
}
return {
show: show,
hide: hide
};
}
var b1 = bubble(..., ...);
b1.show();
var b2 = bubble(..., ...);
b2.show();
See how this frees you from using contrivances like .bind() and underscore-prefixed methods.
One option would be to namespace the event:
$(document).on('click.name', test.bind(this));
$(document).off('click.name');
Example Here
try use jQuery's proxy to get a unique reference of your function.
In this way, when you call $.proxy(test, this), it will check if this function has already been referenced before. If yes, proxy will return you that reference, otherwise it will create one and return it to you. So that, you can always get your original function, rather than create it over and over again (like using bind).
Therefore, when you call off(), and pass it the reference of your test function, off() will remove your function from click event.
And also, your test function should be declared before use it.
var test = function(){
console.log('click');
};
$(document).on('click', $.proxy(test, this));
$(document).off('click', $.proxy(test, this));
http://jsfiddle.net/aw50yj7f/
Please read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
bind creates a new function therefore doing $(document).on('click', test.bind(this)); is like $(document).on('click', function(){}); and each time you execute it you invoke a new anonymous function thus you dont have a reference to unbind.
If you would do something like:
var test = function(){
console.log('click');
};
var newFunct = test.bind(this);
$(document).on('click', newFunct );
$(document).off('click', newFunct );
It should work fine
e.g: http://jsfiddle.net/508dr0hv/
Also - using bind is not recommended, its slow and not supported in some browsers.
rather than binding this to the event, send this as a parameter:
$("#DOM").on("click",{
'_this':this
},myFun);
myFun(e){
console.info(e.data._this);
$("#DOM").off("click",myFun);
}
I have a function in html:
<script>
function update_x(obj) {
...
}
</script>
and I call it on click in html with onclick="update_x(this)" (inside of <div class="aaa">).
How can be the same achieved in jquery? I've tried some stuff, like:
$('.aaa').click(update_x);
});
and
$('.aaa').click(function () {
$(this).update_x(1, false);
});
neither won't work...
This would be equivalent:
$('.aaa').click(function () {
update_x(this);
});
But you don't need to use that. Just change your function to
function update_x(event_obj) {
// 'this' will be the clicked object automatically
// plus, you have further info in the event object
}
$('.aaa').click(update_x);
Make sure $('.aaa').click(update_x) is called after the element with class "aaa" exists in the DOM. You can wrap that code in a document.ready handler, or use event delegation.