How to call custom jquery function onClick - javascript

Hi. I am new to jQuery.. I want to know how to call custom jQuery function by onClick attribute of HTML. This was the basic I was trying.Further I want to make parametrised function and want to call that function onClick attribute.
my jQuery function is:
jQuery.fn.myFadeIn=function() {
return $('#fadeInDiv').fadeIn();
};
and the HTML is:
<input type="radio" name="contentCalls" class="radioButton" id="Calls" onclick="myFadeIn();">
<div id="fadeInDiv">
div to open
</div>
Thanks!

This plugin alert()s the ID of each matched element:
jQuery.fn.alertElementId = function()
{
return this.each(function()
{
alert(this.id);
});
};
And to use it:
// alert() each a-element's ID
$("a").click(function ()
{
$(this).alertElementId();
});

Replace:
jQuery.fn.myFadeIn=function() { return $('#fadeInDiv').fadeIn(); };
With:
var myFadeIn=function() { return $('#fadeInDiv').fadeIn(); };
(Assuming you are running this in the global scope)

You need to assign this custom function to some element's click handler, as in:
$("#Calls").click($.myFadeIn);
What is important to note is that the function you have added to jQuery through its jQuery.fn syntax should be available as part of the $ or jQuery JavaScript objects.

Related

onclick generates invalid function

I have a variable that is attached to a function. I am trying to use that variable in an onclick event.
This is what I am doing
var show = function() {
console.log("hello");
};
$(container).append(
"<div class='info' onclick=" + show + ">Show</div>"
);
However the generated html comes out like this
<div class="info" onclick="function()" {="" console.log("hello");="" }="">
Show
</div>
Any idea how I can fix this so that when I click the div my function gets called ?
You can simply do like this, Just make show a function and call it on click.
This will work
<script>
function show() {
console.log("hello");
}
$(container).append(
'<div class="info" onclick="show()">Show</div>'
);
</script>
This is kind of an unusual approach to what you're trying to do. I think it would be more idiomatic in jQuery to either
a) define the element first, with event handler, and then append it,
$("<div>Show</div>", {
"class": "info",
on: {
click: function(e) {
console.log("Hello");
}
}
}).appendTo($(container));
or
b) append a new element and then add an event handler to it after appending it.
$(container).append("<div class='info'>Show</div>");
$(container).children('.info').last().on('click', function(e) { console.log("Hello"); });
Between those two, I'd recommend the first in this case.
The variable show is a function, Then how can you bind it with string?
The code should be like,
$(container).append("<div class='info' onClick='show()'>Show</div>");
try using :
var show = function() {
console.log("hello");
};
$(container).append("<div class='info' onclick="+'show()'+">Show</div>");
This will work.
The reason why your code
var show = function() {
console.log("hello");
};
$(container).append("<div class='info' onclick=" + show + ">Show</div>");
was not working as required as show is an object of type function, so when one uses the function name without the () the variable is replaced bu the code that it consists.
Hope it helps.

Jquery to take value inside function onclick

This little script to take values from select
<script>
jQuery(document).ready(function()
{
var clv1=jQuery("#tr_val").val();
});
</script>
When click over this div and execute function open_win, i need send value of select inside function jQuery("#tr_val").val();
<div onclick="open_win(""+clv1,'test');">Test</div>
The problem it´s i don´t know how writte right syntax for insert value "clv1" inside function open_win when click over div Test
I have only this problem, i try different combinations but no works me never
Thank´s in advanced
You can add a global variable, and on change of your select you can modified that variable.
While on div element you can add id, and write event handler into script tag(here you can access that global variable).
Note: However global variable are not the correct way, but you can do it for learning/testing.
I think this is what you are asking for, I've re-organised things a little. There is now a custom function that you call from the inline onclick of the div. Rather than trying to grab the value on document ready you can do it with the click, I think this simplifies the process.
Let me know if this isn't what you were hoping for.
Demo
// Add a function which you call from the inline onclick
function open_win() {
// Gather the value of the input
console.log( $("#tr_val").val() );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="tr_val" value="one">
<div onclick="open_win()">Test</div>
You may try something like this, store the value on the div's data attribute and then access it inside the function.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
function open_win(){
$(this).data("val", $("#tr_val").val());
console.log($(this).data('val'));
}
</script>
<div onclick="open_win()">Test</div>
<select id="tr_val">
<option value="value1">Value 1</option>
<option value="value2">Value 2</option>
<option value="value3">Value 3</option>
</select>
Note: your open_win function must be defined before calling it.
if you want to get the value of the element with the id tr_val when you click on the div try something like this. put the click event in the javascript as well. Also if you want to run a function like you're trying to do inline you need to have that function defined, but can also use it in the script tags/js file
function open_win(someArg) {
// do something
}
<div class="test-class">Test</div>
<script>
$(document).ready(function() {
var clv1 = $("#tr_val").val();
// anonymous function
$('.test-class').on('click', function(e) {
console.log(clv1);
})
// named function with a parameter
$('.test-class').on('click', function(e) {
open_win(clv1);
})
// if you wanted named function with parameter to look a bit cleaner
// using es6 arrow function
$('.test-class').on('click', (e) => open_win(clv1))
// name function no param (event is the first argument passed in by default but you can't pass params in like this)
$('.test-class').on('click', open_win)
});
</script>
You can use ES6 ways
<h1>Hello World!</h1>
<input id="tr_val" value="element value" hidden>
<div class="open-div" data-text='test'>Test</div>
(function ($) {
$(function () {
let tr_val = $('#tr_val').val();
$('.open-div').on('click', function (e) {
let $this = $(this);
let text = $this.data("text");
console.log(tr_val);
console.log(text);
});
});
})(jQuery);
https://codepen.io/nsivanoly/pen/OemWNM

How to use THIS in child function which is outside of a parent JS

I have an onclick function
$('.modal-trigger').on('click', function() {
$('#'+$(this).data('modal')).show();
calc();
})
<a class="modal-trigger" data-modal="ft-modal">Link</a>
<div id="ft-modal"></div>
I want to add calc() function inside
function calc() {
var tt = document.getElementById('#'+this.getAttribute('data-modal')).document.getElementsByClassName("name-line")[0];
}
The second function is outside (above) the onclick one, and my problem is that I can't figure it out how to perform a search inside the <div> by class name and get the first one that matches the class on plain JS.
And I think that I don't know how to use this properly for this particular case.
You can pass this to the calc function with .call:
calc.call(this);
The calc function needs no change then.
You have to pass this object to the function so that you can refer that inside the function. You can simplify your code by using jQuery:
$('.modal-trigger').on('click', function() {
$('#'+$(this).data('modal')).show();
calc(this); // pass this here
})
function calc(el) {
var tt = $('#'+$(el).data('modal')).find('.name-line')[0];
console.log(tt);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="modal-trigger" data-modal="ft-modal">Link</a>
<div id="ft-modal">
<span class="name-line"></span>
</div>
as suggested in the comments...
$('.modal-trigger').on('click', function() {
...
calc(this);
});
function calc(ele) {
...
}
using document.getElementById in a jQuery script is questionable;
better use $(ele).data('modal') to obtain the data attribute.
of couse both ways would work, nevertheless the readability would be improved
... that's why it is called "write less, do more".

Why isn't this.parent() defined as a function?

JSFiddle
I'm creating a new button element with
$('<button>Remove Entry</button>', { 'type': 'button', 'class': 'delete_button' });
However the neither the type or class attributes seem to be defined, and the console prints an error saying this.parent() is not a function (though I'm positive I enabled jquery)
I'm afraid I've done something simple and stupid, but I can't seem to find anything wrong.
The reason that the attributes are not set on the element, is that you are mixing different uses of the jQuery method.
To use the method in a way that it uses an object for attributes, the first parameter should be a single tag, not a HTML snippet:
$('<button>', { 'type': 'button', 'class': 'delete_button' }).text('Remove Entry');
The reason that this doesn't have a parent method is that it refers to an element, not a jQuery object. You would use $(this) to make a jQuery object from the element reference.
Also, this referers to the new entry button, not the remove entry button, as you are calling the method when you are binding the event. You should call the method when the event happens:
delete_button.click(function() {
remove_entry($(this).parent())
});
Demo: http://jsfiddle.net/Guffa/9TcpB/1/
var entries = 0;
function new_entry() {
entries++
new_entry_div = $('<div>', { 'class': 'entry' }).appendTo('form');
new_entry_div.html('<p><input type="text"></p>')
// delete button
delete_button = $('<button>', { 'type': 'button', 'class': 'delete_button' }).text('Remove Entry');
delete_button.appendTo(new_entry_div);
delete_button.click(function(){
remove_entry($(this).parent());
});
}
function remove_entry(entry) {
entry.remove();
}
$("#newButton").click(function () {
new_entry();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="input">
<form>
</form>
<button id="newButton">New Entry</button>
</div>
You're basically doing this
$("#newButton").click(function() {
new_entry;
});
function new_entry() {
this.parent();
}
but inside the callback for the event handler, this is native JS DOM element, not a jQuery object, so it has no jQuery methods, you have to wrap it first, as in
$("#newButton").click(new_entry);
function new_entry() {
$(this).parent();
}
this contains a DOM element. If you want to use jQuery methods, you have to convert it to a jQuery object with $(this).
jsFiddle Demo
Retain the current context using the call method:
$("#newButton").click(function () {
new_entry.call($(this));//now this in new_entry refers to `$(this)`
})

How to add onclick event in dynamicly add html code via JavaScript?

I try to add some list element in loop via JS. Every element <li>contains <a> tag, now I want to add onClick event in every adding <a> tag. I try to do it so:
liCode = '<li>Text using variable foo: ' + foo + '</li>';
$('#list').append(function() {
return $(liCode).on('click', clickEventOccurs(foo));
});
In clickEventOccurs I just output to console foo. It works in strange way: this event performed just on init when every tag is adding to list, but after click on <a> doesn`t perform anything. How to make it works in proper way - on click performed code in clickEventOccurs?
Firstly, you are assigning not a callback function, but a result of function evaluation. In right way it should be like this:
$('#list').append(function() {
return $(liCode).click(function() {
clickEventOccurs(foo);
});
});
Also, as you are using jQuery you might use benefits of events delegation and use .on method this way:
$('#list').on('click', 'li', function() {
return clickEventOccurs(foo);
});
on() is good for handling events, even to elements which will be created dynamically.
$('body').on('click', '#list li', function(){
clickEventOccurs(foo);
});
http://jsfiddle.net/lnplnp/uGJnc/
HTML :
<ol id="list">
<li>Text using variable foo: foovalue</li>
</ol>
JAVASCRIPT/JQUERY :
function appending(foo) {
liCode = '<li>Text using variable foo: ' + foo + '</li>';
$('#list').append($(liCode));
}
$('#list').on('click', 'li', function() {
return clickEventOccurs($("a", this).text());
});
function clickEventOccurs(v){
console.log(v.split(":")[1].trim());
}
appending("foo1");
appending("foo2");
appending("foo3");
To pass a variable to that function you'll have to make a second anonymous one, otherwise your clickEventOccurs function will be called at assignment, not as a callback.
$('#list').append(function() {
return $(liCode).click(function() {
clickEventOccurs(foo)
});
});

Categories

Resources