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.
Related
I'm sure this is something simple that I am missing but I'm at a loss.
I have this block of jQuery:
jQuery("span.frm_inline_total").digits();
jQuery(".frm_input_group").on("blur", "input", function () {
jQuery("span.frm_inline_total").digits();
});
jQuery(".frm_range_container input").mouseup(function () {
jQuery("span.frm_inline_total").digits();
console.log("mouse up");
});
jQuery(".frm_range_container input").mousedown(function () {
jQuery("span.frm_inline_total").digits();
console.log("mouse down");
});
That calls a function to place commas in some field numbers. I don't think it's relevant, but here is the function:
jQuery.fn.digits = function () {
return this.each(function () {
jQuery(this).text($(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
})
}
My issue is this. Everything works except when I try to call digits() using mouseup(). It logs the mouseup() event with 'console.log', and the mousedown() event correctly works, but no mouseup(). ...alert("mouse up") works, just not 'digits'.
For what it's worth, I'm placing this event on a built-in slider in a drag-and-drop website I am editing. My "development" is limited to client side code. There is already an event on it to retrieve the new values that I thought might be interfering, but then I don't understand why it would fire logs or alerts.
Assuming your HTML structure is something like this:
<div class="frm_range_container">
<div class="frm_input_group">
<span class="frm_inline_total">Value to replace</span>
<input value="Click me"></input>
</div>
</div>
and the rest of your code works, changing the code like below should produce desired output.
// added logs to check in console, digits function is the same
$.fn.digits = function () {
console.log('digits'); // test to see if reaches digits() function
return this.each(function () {
// this should be the correct element.
$(this).text(
$(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
);
})
}
$(".frm_range_container input").on('mouseup mousedown', function (e) {
console.log(e.type);
$("span.frm_inline_total").digits();
});
If you want to only target span.frm_inline_total contained in each frm_range_container, you can use $("span.frm_inline_total", this).digits(); for that
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
});
I have a weird problem. I have a freight calculation field to be executed if the User deletes a digit input , I hide one content. While running the script in chrome console, it is loaded, but when using the call in html, js it does not run. This is what I have.
https://jsfiddle.net/diasbass/u3xr0921/
jQuery(document).ready(function($) {
$("#btnFreteSimulacao").click(function() {
$("#txtCep").keyup(function() {
if ($("#txtCep").val()) {
$('p.montagem').hide();
} else {
$('p.montagem').show();
}
});
});
});
The keyup event handler is inside the click function, probably it is of no use.
Also need to check $("#txtCep").val().length for showing and hiding the p.montagem
jQuery(document).ready(function($) {
$("#txtCep").keyup(function() {
if($("#txtCep").val().length ==0) {
$('p.montagem').hide();
} else {
$('p.montagem').show();
}
});
});
jsfiddle
Here you are mixing two asynchronous events 1) Button click 2) Input keyup. Your code expects to work when both are happening same time. I would suggest remove dependency on one event. Like below.
$( "#btnFreteSimulacao" ).click(function() {
// $("#txtCep").keyup(function() {
if($("#txtCep").val()) {
$('p.montagem').hide();
} else {
$('p.montagem').show();
}
});
// });
});
If thats not possible, try to look towards promises.
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.
I have one code block which I want to invoke in different scenarios when a click is triggered, depending on whether the event is direct or is delegated.
But on changing the code to on, it only works partially.
I have one code:
$(document).on('click','.selected-option',function(event){
//lot of code
I want to use:
$('.selected-option').click(function(event){ //lots of code }
I want to use this together like:
if (some condition)
{
$(document).on('click','.selected-option',function(event){
}
else
{
$('.selected-option').click(function(event){
}
and want to use the same code.
You don't have to use anonymous functions to handle events. Just write a regular function:
function handleClick(event) {
// lots of code
}
Then bind the function to as many events as you want:
if (some condition) {
$(document).on('click','.selected-option', handleClick);
else {
$('.selected-option').click(handleClick);
}
define a function and do the job;
var funCalled = function(){
//your detailed actions
}
and call it in different conditions!
if (some condition) {
$(document).on('click','.selected-option',function(event){
funCalled()
})
} else {
$('.selected-option').click(function(event){
funCalled()
});
}
var testfunction = function(currentObj){
// your code here
}
if (some condition)
{
$(document).on('click','.selected-option',function(event){
testfunction($(this));
});
}
else {
$('.selected-option').click(function(event){
testfunction($(this));
});
}