JQuery to Javascript click function - javascript

Need help with converting JQuery to Javascipt.
Im trying to is, by clicking the ‘Change Size’ button result in a call to the new sizeObject.changeSize function and a change to both the Size object’s isSize
variable and the size of the light div in the browser
I dont want to change the HTML. Need help with converting the .click function
var sizeObject;
function createSize(){
//Size object initialisation
sizeObject = new Size();
// size-related event handlers
$('#change').click(function(){
Size.changeSize();
});
}

Instead of :
$('#change').click(function(){
Size.changeSize();
});
Use :
var elem = document.getElementById("change");
elem.addEventListener("click", function() {
Size.changeSize();
});

The regular Javascript function for binding event handlers is addEventListener.
document.getElementById("change").addEventListener("click", function() {
sizeObject.changeSize();
});

Related

Append method to button created in other method in javascript

It is possible add method to event onclik. This code create event onclick in html "onclick='alert("TEST");undefined'". I care to get "onclick='alert("TEST");stdaction('t1')'" where stdaction('t1') is function in class Button
function Button(id,onclick){
this.id = id;
this.onclick= onclick;
}
Button.prototype.create = function(){
var button = $('<div>');
button.attr('id',this.id);
button.html('Default');
button.attr('onclick',this.onclick+';'+this.stdaction(this.id)); // this is problem
return button.prop('outerHTML');
}
Button.prototype.stdaction = function(id){
$('#'+id).addClass('std-active');
}
var oneButton = new Button('t1','alert("TEST")');
$('#newButton').append(oneButton.create());
I changed as suggested Paflow is better, but I wanted to make a function connected running the onclick even had a separate method
https://jsfiddle.net/uevckbe0/
Instead of
button.attr('onclick',this.onclick+';'+this.stdaction(this.id)); // this is problem
write something like
button.addEventListener('click', function() {
this.onclick();
this.stdaction(this.id)
}.bind(button));

JS prevent a function from running as onclick event

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

jQuery off() is not unbinding events when using bind

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);
}

Javascript pass parameter to function

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 ");
}
}

Appending existing onClick value

I am using javascript and need to grab the value of an existing onclick and append to it. I am not trying to replace the current onclick, I am trying to append to the front, or end, of it. But all different iterations of this effort are failing.
Quick example:
<pre>
<a href="blah" id="tabA" onclick="alert("this");"
<script>
function test() {
alert("that") ;
}
document.getElementById('tabA').onclick = "test();" + document.getElementById('tabA').getAttribute('onclick') ;
</script>
</pre>
When using the .onclick event you should use function and then the action:
document.getElementById("tabA").onclick = function()
{
alert("hello world")//this will work
}
document.getElementById('tabA').onclick = "test();" + document.getElementById('tabA').getAttribute('onclick') ;//fail since events are not variables to store values.
So, what you whatever you are tring to do, in that way it wont work.
I don't know if I had got your point.
My solution is
tabA
<script>
function test() {
alert("that") ;
}
var oldClick = document.getElementById('tabA').getAttribute('onclick') ;
var newClick = function(){
test();
eval(oldClick);
}
document.getElementById('tabA').onclick = newClick;
</script>
when I click the 'tabA', it alerts 'that' then 'this'.
http://jsfiddle.net/x3Xds/
I know this is quite old but, I needed to do the same thing.
I got around this by using an event;
obj.addEventListener('click', function(){ test(); }, false);

Categories

Resources