jQuery mouseup() issue - javascript

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

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

Jasmine doesn't seem to be calling my method

I am new to Jasmine and seem to be struggling to get what I think is a fairy standard kind of thing running.
I am loading an HTML file via a fixture and trying to call a click on an element on the dom. This I would expect result in the call to the method of the JS file I am trying to test. When I try and debug this in developer tools the method that should be called in my js file never hits a breakpoint. As such I assume that code is not being called and therfore does not toggle the expand/collapse class.
My test:
describe("userExpand", function () {
beforeEach(function () {
loadFixtures('user-expand.html');
//userControl();
//this.addMatchers({
// toHaveClass: function (className) {
// return this.actual.hasClass(className);
// }
//});
});
//this test works ok
it("checks the click is firing", function () {
spyOnEvent($('.expanded'), 'click');
$('.expanded').trigger('click');
expect("click").toHaveBeenTriggeredOn($('.expanded'));
});
//this doesn't
it("checks the click is changing the class", function () {
//spyOnEvent($('.collapsed'), 'click');
var myElement = $('.collapsed');
myElement.click();
expect(myElement).toHaveClass('.expanded');
});
Part of the fixture:
<div class="wrapper">
<div class="row group">
<div class="col-md-1" data-bordercolour=""> </div>
<div class="collapsed col-md-1"> </div>
<div class="col-md-9">None (1)</div>
The JS I am trying to test:
var userControl = function () {
"use strict";
var collapse = '.collapsed';
var expand = '.expanded';
var userList = $(".userList");
function toggleState() {
var currentControl = $(this);
if (currentControl.hasClass('all')) {
if (currentControl.hasClass('expanded')) {
toggleIcon(currentControl, collapse);
userList.find(".user-group-summary").hide()
.end()
.find(".user-group-info").show();
} else {
toggleIcon(currentControl, expand);
userList.find(".user-group-summary").show()
.end()
.find(".user-group-info").hide();
}
} else {
currentControl.parent().nextUntil('.group').toggle();
currentControl.toggleClass("expanded collapsed");
currentControl.parent().find(".user-group-summary").toggle()
.end()
.find(".user-group-info").toggle();
}
};
function toggleIcon(ctrl, currentState) {
var details = ctrl.closest('div.row').siblings('.wrapper');
details.find(currentState).toggleClass('expanded collapsed');
if (currentState === expand) {
details.find('.detail').hide();
} else {
details.find('.detail').show();
}
}
userList.on('click', '.expanded, .collapsed', toggleState);
$('[data-bordercolour]').each(function () {
$(this).css("background-color", $(this).data('bordercolour'))
.parent().nextUntil('.group')
.find('>:first-child').css("background-color", $(this).data('bordercolour'));
});
return {
toggleState: toggleState
};
}();
The code works fine in normal use so I am sure I am missing something obvious with the way Jasmine should be used. Any help would be appreciated.
Update:
I can make the togglestate method fire by using call in the test rather than triggering a click event:
it('checks on click of icon toggles that icon', function () {
var myElement = $('.collapsed');
userControl.toggleState.call(myElement);
expect(myElement).toHaveClass('expanded');
});
This seems a little strange as all the examples I can find are quite happy with click. Gets me off the hook but I would still like to know what I am missing.
It's hard to give a precise hint without the source code. Does click on .collapsed involve asynchronous action(s)? If so, wrapping the test in runs(...); waitsFor(...); runs(...); may solve the problem. Check the Jasmine introduction for how to do this.

Function becomes undefined after first trigger

I have a block of code like so:
function doSomething() {
someVar.on("event_name", function() {
$('#elementId').click(function(e) {
doSomething();
});
});
}
// and on document ready
$(function () {
$('#anotherElemId').click(function () {
doSomething();
});
});
The problem that I'm encountering is that when I call doSomething() from anotherElemId click event(that is binded on document ready) it works as expected, but calling it recursively from elementId click doesn't work.
Any ideas? Thinking is something trivial that I'm missing.
Is someVar an actual jQuery reference to a dom element? (e.g. $('#someitem'))
The second problem is you cant put a .click event inside a function that you would like to instantiate later on. If you are trying to only allow #elementId to have a click event AFTER some previous event, try testing if a tester variable is true:
var activated = false;
$(function () {
$('#anotherElemId').click(function () {
activated = true;
});
$('#secondElemId').on("event_name", function() {
if (activated) {
// code that happens only after #anotherElemId was clicked.
}
});
});

Making my mouseevent coded in jquery a lot more elegant

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.

Using unbind, I receive a Javascript TypeError: Object function has no method 'split'

I've written this code for a friend. The idea is he can add a "default" class to his textboxes, so that the default value will be grayed out, and then when he clicks it, it'll disappear, the text will return to its normal color, and then clicking a second time won't clear it:
$(document).ready(function() {
var textbox_click_handler = function clear_textbox() {
$(this).removeClass('default');
$(this).attr('value', '');
$(this).unbind(textbox_click_handler);
};
$(".default").mouseup(textbox_click_handler);
});
The clicking-to-clear works, but I get the following error:
Uncaught TypeError: Object function clear_textbox() { ... } has no method 'split'
what is causing this? How can I fix it? I would just add an anonymous function in the mouseup event, but I'm not sure how I would then unbind it -- I could just unbind everything, but I don't know if he'll want to add more functionality to it (probably not, but hey, he might want a little popup message to appear when certain textboxes are clicked, or something).
How can I fix it? What is the 'split' method for? I'm guessing it has to do with the unbind function, since the clearing works, but clicking a second time still clears it.
You can do it like this:
var textbox_click_handler = function(e) {
$(this).removeClass('default')
.attr('value', '')
.unbind(e.type, arguments.callee);
};
$(function() {
$(".default").mouseup(textbox_click_handler);
});
Or use the .one function instead that automatically unbinds the event:
$(function() {
$(".default").one('mouseup', function() {
$(this).removeClass('default').attr('value', '');
});
});
The unbind needs an event handler while you are specifying a function to its argument thereby giving you the error.
I am not sure if this is really different but try assigning the function to a variable:
var c = function clear_textbox() {
$(this).removeClass('default');
$(this).attr('value', '');
$(this).unbind('mouseup');
}
and then:
$(".default").mouseup(function(){
c();
});
if you don't want to completely unbind mouseup, check for the current state using hasClass(). No need to unbind anything.
$(document).ready(function() {
$('.default').bind('mouseup', function(e) {
var tb = $(this);
if(tb.hasClass('default')) {
tb.removeClass('default').val('');
}
});
});
Make sure you are unbinding mouseup:
function clear_textbox() {
$(this).removeClass('default');
$(this).attr('value', '');
$(this).unbind('mouseup');
}
$(function() {
$('.default').mouseup(clear_textbox);
});
Also I would write this as a plugin form:
(function($) {
$.fn.watermark = function(settings) {
this.each(function() {
$(this).css('color', 'gray');
$(this).mouseup(function() {
var $this = $(this);
$this.attr('value', '');
$this.unbind('mouseup');
});
});
return this;
};
})(jQuery);
so that your friend can simply:
$(function() {
$('.someClassYourFriendUses').watermark();
});

Categories

Resources