equivalent of onclick="update_x(this)" in jquery? (call function) - javascript

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.

Related

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, CSS, event handlers

I am supposed to use Jquery to call a function that changes a div's visibility using css. This is my JQUERY
alert("Interactive on line");
function changeView(page)
{
alert("Handler for click() called. ");
if(page === 'home)
{
$('#HomeTab'.css(display=='none'));
}
}
$('#HomeTab').on('click', { page:'home'}, changeView());
I used the alert statement inside the changeView to see if changeView ever gets called and it does not. The initial alert before the changeView function does get called, so the script is linked correctly.
Thank you in advance!
Refer .on( events [, selector ] [, data ], handler )
(a) You are invoking/calling function, not assigning it as handler, Remove () after function name.
(b) data object could be accessed using event.data.KEY
(c) Also correct the typo while using .css method, it is jQueryElement.css(PROPERTY,VALUE)
function changeView(e) {
alert("Handler for click() called. ");
if (e.data.page === 'home') {
$('#HomeTab').css('display', 'none');
//OR $('#HomeTab').hide();
}
}
$('#HomeTab').on('click', {
page: 'home'
}, changeView);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id='HomeTab'>Home Tab</div>

Jquery : binding a function to a click event of an element already bound

There's a first binding done on the click event of an element :
$("#element").on("click", function() {
//actions of function1
});
I would like to be able to bind another function to it, preserving the actions of the precedent function. Something like :
function elementClickAdd(elementId,newFunction){
//here, get the actions of function1
$("#"+elementId).on('click', function() {
//perform actions of function1
newFunction();
});
}
But I can't figure out how to make this.
Could you help me please ?
Thanks
Edit : thanks for helping, the solution is here : https://jsfiddle.net/9bo6dvmb/1/ enjoy :)
If you creating the id dynamically, you can call the event after generating only, so write this line after appending the ID. Like below
function dynamic_bind()
{
$("#test").append("<div id='tt'>test example</div>");
$("#tt").on("click",function(){
hi();
});
}
function hi()
{
alert("executed");
}
dynamic_bind();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">Sample Div</div>

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

jquery: function to end another function

$('#start') executes the function myFunction() and $('#stop') end it. How do I stop myFunction() from executing?
function myFunction() {
$(document).mousemove(function(e) {
$('#field').html(e.pageY)
});
}
$('#start').click(function() {
myFunction();
});
$('#stop').click(function() {
//stop myFunction
});
As Daniel pointed out, you actually want to unbind the event handler. You can use unbind for this:
$('#stop').click(function() {
$(document).unbind('mousemove');
});
But this will also remove all other mousemove event handlers, that might be attached by other plugins or similar (I mean, you attach to the document element not a "custom" element, so it can be that other JavaScript code also binds handlers to this element).
To prevent this, you can use event namespaces. You would attach the listener with:
function myFunction() {
$(document).bind('mousemove.namespace', function(e) {
$('#field').html(e.pageY);
});
}
and unbind:
$('#stop').click(function() {
$(document).unbind('mousemove.namespace');
});
This would only remove your specific handler.
You want to use the jQuery bind and unbind methods. For example:
function myFunction() {
$(document).mousemove(function(e) {
$('#field').html(e.pageY)
});
}
$('#start').bind('click.myFunction', function() {
myFunction();
});
$('#stop').bind('click', function() {
$('#start').unbind('click.myFunction');
});
You're not stopping the function from executing. Your myFunction() simply attaches a callback to an event listener, which is called whenever the mouse is moved on the document. The callback function is invoked and is terminated immediately.
You'd simply want to unbind the callback from the event listener. Check out the other answers for concrete examples.
A better way would be to use bind and unbind, like so:
function myFunction() {
$(document).mousemove(function(e) {
$('#field').html(e.pageY)
});
}
$('#start').bind('click', myFunction);
$('#stop').click(function() {
$('#start').unbind('click', myFunction);
});

Categories

Resources