I have two buttons: one with class btn-star, and the other with btn-current. I am calling an independent function on each of their clicks. But now, I want to call only one function when they are called.
My code is similar to this:
$('document').ready(() => {
$(document).on('click', '.btn-star', function () {
// Do stuff
}
$(document).on('click', '.btn-current', function () {
// Do stuff
}
}
You can try this code. You can use multiple elements click event for one action with only one line code, Just use a comma for separating elements
$('document').ready(() => {
const myFunction= () => {
// Your Code here...
}
$(document).on('click', '.btn-current, .btn-current', function () {
myFunction();
}
}
You can define a function separately and pass it in as callback for both buttons' on click handler. For example -
$('document').ready(() => {
const commonFunc = () => {
// do common stuffs here
}
$(document).on('click', '.btn-star', commonFunc());
$(document).on('click', '.btn-current', commonFunc());
}
Hope that helps!
If you want to call the same function you can select your two button classes, using a simple j-query expression:
$('.btn-star, .btn-current').click(function() {
// Do stuff
}
Ad your selectors separated by a comma, inside the quotation marks.
You can read more about j-query selector at this link:
https://www.sitepoint.com/comprehensive-jquery-selectors/
A little shorter code...
$('document').ready(() => {
function commonFunc() {
//do stuffs here
}
$('.btn-star, .btn-current').on('click', commonFunc);
}
you can try like this:
function test()
{
//your code
}
$(".btn1, .btn2").on("click", funciton(){
test();
});
Try below code
$('.btn-star, .btn-current').on('click', function () {
// Do shared stuff
});
Reference: http://api.jquery.com/on/
Why is [Javascript] tagged on this post? If it is meant to be there, I'm assuming you are going to accept javascript responses right?
If you're going javascript, it is much easier, and you can just add a onClick='function()' to your html code and do your functions in there.
<html>
<head>
<script>
function buttonFunction(buttonName){
//EDIT 3.0: You can make one button do the same as the other button, but you can also make it do something else at the same time!
if(buttonName == 'btn-star'){
//other code such as:
alert("Stars are awesome!");
}
alert("You just clicked " + buttonName);
}
</script>
</head>
<body>
<div id='button1'>
<button id='btn-star' onclick='buttonFunction("btn-star")'>btn-star</button>
</div>
<br/>
<div id='button2'>
<button id='btc-current' onclick='buttonFunction("btn-current")'>btn-current</button>
</div>
</body>
</html>
If you want, you can also additionally make one button do the same as the other, and then after that do something different like I did in this snippet.
P.S: I'm just assuming javascript is allowed, because after all, it is tagged on this post.
EDIT: I showed you an example of one button doing slightly differently then the other, but still the same in a way
ANOTHER EDIT: You can do a lot of stuff with this, added ideas on what else you could do with this snippet.
You can try
$('.btn-star , .btn-current').on('click', function () {
//do something common for elements
});
Related
I know my question have answer in the past but I don't have the vocabulary to find this.
I call a JavaScript function like this:
Voir +
This function change the state of the element .stats-table but I want to know which button have been clicked to call this function?
Better : can I have a jQuery object of this button?
Try to pass the this reference to know which button was clicked,
HTML:
Voir +
JS:
function showTable(selec,elem){
var currentElem = $(elem); //Clicked element
}
If you don't want to change the signature of the function and the way you invoke it (as others have suggested), you can use the global window.event to identify the clicked element:
function showTable(selector)
{
var clickedElement = window.event.target;
//...
}
See MDN.
When you use jQuery, you might consider refactor your code like this:
$(document).ready(function(){
$('.show-table-link').on('click', function(){
var $usedButton = $(this)
showTable('.stats-table')
}
})
Voir +
It's good practice to attach the on click handler instead of writing it inline. Further reading document.ready and jQuery event basics.
You can pass any value or id and your can identify the function
<script type="text/javascript">
function showTable(clss_name,fun_id)
{
if(fun_id=='A1')
{
alert("First function Executed");
}
if(fun_id=='A2')
{
alert("Second Function is executed");
}
}
</script>
......
......
......
Voir +
Voir2 +
If your function is like this:
function showTable(selec) {
// some code
}
You can get the clicked element like this, using this:
function showTable(selec) {
// some code
var clickedElem = this;
}
Good Day, this maybe a silly question :) how can I pass a parameter to an external javascript function using .on ?
view:
<script>
var attachedPo = 0;
$this.ready(function(){
$('.chckboxPo').on('ifChecked', addPoToBill(attachedPo));
$('.chckboxPo').on('ifUnchecked', removePoToBill(attachedPo ));
});
</script>
external script:
function addPoToBill(attachedPo){
attachedPo++;
}
function removePoToBill(attachedPo){
attachedPo--;
}
but Im getting an error! thanks for guiding :)
You need to wrap your handlers in anonymous functions:
$('.chckboxPo')
.on('ifChecked', function() {
addPoToBill(attachedPo);
})
.on('ifUnchecked', function() {
removePoToBill(attachedPo);
});
You can also chain the calls to on as they are being attached to the same element.
If your intention is to count how many boxes are checked, via passing variable indirectly to functions try using an object instead like this:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/pBkhX/
var attachedPo = {
count: 0
};
$(function () {
$('.chckboxPo')
.on('change', function () {
if ($(this).is(':checked')) {
addPoToBill(attachedPo);
} else {
removePoToBill(attachedPo);
}
$("#output").prepend("" + attachedPo.count + "<br/>");
});
});
function addPoToBill(attachedPo) {
attachedPo.count++;
}
function removePoToBill(attachedPo) {
attachedPo.count--;
}
If it is not doing anything else you can simplify the whole thing to count checked checkboxes:
$(function () {
var attachedPo = 0;
$('.chckboxPo')
.on('change', function () {
attachedPo = $(".chckboxPo:checked").length;
});
});
"DOM Ready" events:
you also needed to wrap it in a ready handler like this instead of what you have now:
$(function(){
...
});
*Note: $(function(){YOUR CODE HERE}); is just a shortcut for $(document).ready(function(){YOUR CODE HERE});
You can also do the "safer version" (that ensures a locally scoped $) like this:
jQuery(function($){
...
});
This works because jQuery passes a reference to itself through as the first parameter when your "on load" anonymous function is called.
There are other variations to avoid conflicts with other libraries (not very common as most modern libs know to leave $ to jQuery nowadays). Just look up jQuery.noConflict to find out more.
$(this).click(function() {
clicked($(this));
});
How do I minimize this code to one line?
Tried this - doesn't work:
$(this).click(clicked(this));
It will be used then like this:
function clicked(element) {
element.css('...');
// some other code
}
You can pass the clicked function directly:
$(this).click(clicked);
but you'll need to change your clicked function to wrap the element.
function clicked() {
$(this).do("whatever")
}
Regarding your updated question, you can have clicked return a function if you want.
function clicked(element) {
return function() {
element.css('...');
// some other code
}
}
So then you can do this:
$(this).click(clicked($(this)));
But I'd personally change your clicked function to work like the first version.
How can I achieve this?
for each pages I have attached a unique class-name so I can target them by css later.
body.pageHome
about.pageAbout
contact.pageContact
I want to run a function but only targeting the homepage.
eg.
if($('body').hasClass('pageHome')) {
callMe;
}
function callMe() {
alert('I am Home!');
}
It looks like you're close. To call callMe, you'll want parenthesis to indicate that it's a function call:
if($('body').hasClass('pageHome')) {
callMe();
}
Your forgot the parenthesis when you called callMe:
function callMe() {
alert('I am Home!');
}
if($('body').hasClass('pageHome')) {
callMe();
}
Does that help?
Concept should work fine as long as you are wrapping code in
$(function(){ /* run code*/ })
and you need to add "()" to callme();
I wrote this in order to fix the problem IE has with select drop down lists being truncated if their options were longer than the default value of the select. Now it works fine but I want to improve the code in order to learn how to write things in a much more useable fashion.
$(document).ready(function() {
if ($.browser.msie) {
$('select').focus(function() { $(this).addClass('expand').removeClass('clicked'); })
$('select').blur(function() { $(this).removeClass('expand clicked'); })
$('select').mousedown(function () { $(this).addClass('expand').removeClass('clicked'); } )
$('select').hover(function () { }, function () {if (!$(this).hasClass('clicked')) { $(this).removeClass('expand'); $(this.blur()) }})
$('select').click (function() { $(this).toggleClass('clicked'); })
$('select').change(function(){ $(this).removeClass('expand clicked'); $('select.widerIE').blur() })
}
});
I tried making functions which were called by each event but that seemed to fail eg:
$('select').click(test (a))
function test (a) {
$(a).addClass('expand').removeClass('clicked')
}
It's not clear to me what you're trying to achive. One thing is sure - you can't define a event handler like that (see note below):
$('select').click(test (a))
Note: Technically, you could define your event handler like in code above. For that to work, function test would have to return a function that would be actual handler for the event.