check for className before running the function - javascript

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

Related

Call single function for multiple classes

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

how to pass parameter in jquery using .on?

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.

Minimize click()

$(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.

Run a function inside a function

I have this:
function cool(){
function alsocool(){
}
}
And I run the cool() on button click:
$(selector).on('click', function(){
cool();
}
How can I run the cool() and the alsocool() from the same click? Note that I don't want to do:
function cool(){
function alsocool(){
}
alsocool();
}
If I do :
$(selector).on('click', function(){
cool(); alsocool();
}
it doesn't work.
Is it possible to run a function inside a function on the same call?
EDIT:
I DO WANT to pass cool() since obviously alsocool() is not recognized once its inside function cool() BUT cool(); is passed from many selector thus I want to know from which selector is passed and take the appropriate action.
Example I want something like this:
function cool(){
// If this was called by button1, run alsocool() else bypass it
function alsocool(){
}
// some code goes here
}
$("#button1").on('click', function(){
cool(); alsocool();
// If button1 clicked, run cool AND alsocool
}
$("#button2").on('click', function(){
cool(); // If button2 clicked, run cool ONLY.
}
The answer is simple: It is impossible.
The inner function is local to the containing function's scope so unless that function calls it, it cannot be called at all.
If you want both functions to be reachable from outside, define alsocool outside cool, i.e. on the same level as cool.
As per your comment, here's a way that would use a parameter to determine if the inner function should be called or not:
function cool(callInner){
function alsocool(){
}
if(callInner) {
alsocool();
}
}
If you do
function cool() {
function alsocool() { ... }
}
Then 'alsocool' only exists while the cool() function is executing. It will not be externally accessible.
You'd want:
function cool() { ... }
function alsocool() { ... }
$(selector).click(function() {
cool();
alsocool();
}):
The problem is that because you've defined the function alsocool within cool, it's visibility is limited to that scope.
Because of this, you can only call the function alsocool from within cool.
You can, of course, move the declaration of alsocool outside of cool, and this will still allow you to call alsocool from within cool, but you will loose access to the scope of cool from within alsocool.
You could also limit the invocation of alsocool inside cool depending on a parameter passed, if this is a viable option for you;
function cool(alsoAlsoCool){
function alsocool(){
}
if (alsoAlsoCool) {
alsocool();
}
}
// cool(true) will call it, but cool() or cool(false) won't.
You can't do that. alsocool only exists inside cool, the click handler has no idea alsocool exists.
If you don't want to call alsocool from inside cool, then you're gonna have to make alsocool global.
I don't understand why you want to do that, but you can do this :
function cool()
{
arguments.callee.alsoCool = function() {
alert("also cool");
};
alert("cool");
}
$("#b").click(function() {
cool();
cool.alsoCool();
});
Live demo: http://jsfiddle.net/ENqsZ/
Alternatively, as a Rocket suggested, you can do this :
function cool()
{
alert("cool");
return function() {
alert("also cool");
};
}
$("#b").click(function() {
var alsoCool = cool();
alsoCool();
});

why is this code not targeting the right selector

This function is supposed to change the background color of the object being clicked
function colorMe(){
$(this).css('background-color', 'red');
}
I call it like this
$('.colorme').click(colorMe);
and it changes the background of this div
<div class="colorme">Color Me</div>
The problem is that I want to do something else before running colorMe. So I can't use just $('.colorme').click(colorMe);. What I'm trying to do is something like this
$('.colorme').click(function(){
alert('something happens first, then colorMe is called');
colorMe(); //I call colorMe here..
$(this).colorMe(); //I also tried this, but it's not working
});
but it's not affecting the div. I think it lost track of the div to affect. Do I need to pass it and how?
function colorMe(elt){
$(elt).css('background-color', 'red');
}
$('.colorme').click(function(){
alert('something happens first, then colorMe is called');
colorMe(this); //I call colorMe here..
});
To call a function on a jQuery object like you did here
$(this).colorMe()
you would have to build a plugin (I edited it to add a class)
// css
.red {
background: red;
}
// js
(function($) {
$.fn.extend({
colorMe: function() {
this.addClass("red");
},
unColorMe: function() {
this.removeClass("red");
}
});
})(jQuery);
Then you would be able to do
$(".a_class").colorMe();
$(".a_class").unColorMe();
You should use the .addClass() method.
function colorMe(element){
element.addClass('my-red-class');
}
$('.colorme').click(function(){
colorMe(this);
});
And in your css file you have a class called 'my-red-class' (use a better name!)
.my-red-class { background-color: red; }
And you can also easily remove the css:
function unColorMe(element){
element.removeClass('my-red-class');
}
function colorMe(){
$(this).css('color', 'red');
}
using call()
$('.colorme').click(function(){
alert('something happens first, then colorMe is called');
colorMe.call(this);
});

Categories

Resources