Reusing code between different event handlers - javascript

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

Related

Do I need to remove and replace event handlers with JQuery to swap them?

I want the events click and touchstart to trigger a function.
Of course this is simple with JQuery. $('#id').on('click touchstart', function{...});
But then once that event is triggered, I want that same handler to do something else when the events are triggered,
and then later, I want to go back to the original handling function.
It seems like there must be a cleaner way to do this than using $('#id').off('click touchstart'); and then re-applying the handler.
How should I be doing this?
You can create a counter variable in some construct in your javascript code that allows you to decide how you want to handle your event.
$(function() {
var trackClicks = (function() {
var clicks = true;
var getClicks = function() {
return clicks;
};
var eventClick = function() {
clicks = !clicks;
};
return {
getClicks: getClicks,
eventClicks: eventClicks
}
})();
$('#id').on('click touchstart', function {
if (trackClicks.getClicks()) {
handler1();
} else {
handler2();
}
trackClicks.eventClick();
});
function handler1() { //firsthandler};
function handler2() { //secondhandler};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The way I would do this is by creating a couple of functions for the handler function to call based on certain flags. Sudo code would be something like this:
function beginning_action() {
...
}
function middle() {
...
}
var beginning_state = true;
$('#id').on('click touchstart', function{
if(beginning_state) {
beginning_action();
} else {
middle();
}
});
Then all you need to do is change the variable beginning_state to change which function is called. Of course you would give them better names that describe what they do and not when they do it.
Additionally, if you want the handler to call more than two functions you can change the beginning_state variable from a boolean to an int and check it's value to determine which function to call.
Good luck!

Defining generic function jquery

I have a simple function that shows a div when the user clicks on a given checkbox. I'd like to have the same behaviour on another checkbox, so that's why I'd like to generalize it as a function passing the element to be shown.
But I'm not aware of the syntax on Jquery to do so. And it's triggering automatically when the page loads. Does anybody has an idea?
Code:
$(document).ready(function() {
$("#transcricao").change(
function(){
if ($('.form_transcr').css('display') === 'none') {
$('.form_transcr').fadeIn();
} else {
$('.form_transcr').fadeOut();
}
}
); //This is working fine!
$("#traducao").change( show_hide($('.form_trad')) );
//This is auto-trigerring without user action...
});
Here's my function:
function show_hide($elm){
//This is the "generalized" function that I'd like to use on both
//checkboxes, just passing the element.
if ($($elm).css('display') === 'none') {
$($elm).fadeIn();
} else {
$($elm).fadeOut();
}
}
Its auto-triggering without user action because you are invoking it.
Use
$("#traducao").change(function () {
show_hide($('.form_trad'));
});
As you are passing jQuery object so use it directly
function show_hide($elm) {
//This is the "generalized" function that I'd like to use on both
//checkboxes, just passing the element.
if ($elm.css('display') === 'none') {
$elm.fadeIn();
} else {
$elm.fadeOut();
}
}
The argument to .change() should be a function. You're not passing a function, you're calling the function.
$("#traducao").change(function() {
show_hide($('.form_trad'));
} );
BTW, your show_hide function seems to be equivalent to jQuery's fadeToggle method, so it can be:
$("#traducao").change(function() {
$(".form_trad").fadeToggle();
});

if ignores the condition JQuery

I'm trying to set up a div that can only be clicked once, but my if keeps ignoring the condition and I really dont know why.
$(document).ready(function() {
var defaultState = true;
if (defaultState) {
defaultState = false;
$("#element").click(function() {
//Do stuff to elements
}
});
I tried solving it a different way. I want this condition only to fill one div with context from another one, but only one single time. So I tried making the condition like this: if($("#element").html().length === 0) I even checked with the console for the value of my condition, and even if it was at 5000, clearly not 0 anymore, it kept ignoring my condition and went into the if.
Once you bind the click handler, it's bound. From that point, until you unbind it, that handler will always be triggered.
It sounds like one() would be what you're looking for:
$('#element').one('click', function() {
//...
});
That will only trigger once.
The event handler is already attached that first time through, right after the document.ready runs.
You can just use the jQuery .one() event handler.
jQuery .one() documentation
$("#element").one('click', function() {
//Do stuff to elements
});
$(document).ready(function() {
$("#element").one('click', function() {
//Do stuff to elements
});
});
OR
$("#element").on('click', function(){
//Do what you want
});
//Later in your code
$("#element").off('click');
If you're set on using a flag variable you can do it like this too:
$(document).ready(function() {
var defaultState = true;
$("#element").click(function(e) {
if (defaultState) {
//Do what you want
}
defaultState = false;
}
});
Once you have added a event listener $("#element").click(function() { it will be bounded to that element. But what you can do it to put your if inside the click function and give false to your flag variable once inside the if.
The advantage is you can give the variable true again, and you click will run "again".
$(document).ready(function () {
var defaultState = true;
$("#element").click(function () {
if (defaultState) {
defaultState = false;
//Do stuff to elements
} else {
return false;
}
});
});

I have a nested function in a function but my code won't clear the display correctly. I am not getting an error in console?

$(document).ready(function()
{
function clearTheDisplayInitial()
{
$(document.getElementById('Resume')).hide();
$(document.getElementById('CodingExamples')).hide();
$(document.getElementById('AboutMe')).hide();
}
function clearTheDisplay()
{
$(document.getElementById('Resume')).fadeOut(900);
$(document.getElementById('CodingExamples')).fadeOut(900);
$(document.getElementById('AboutMe')).fadeOut(900);
$(document.getElementById('mainMenu')).fadeOut(900);
}
$("#displayResume").click(function()
{
clearTheDisplayInitial();
$(document.getElementById('Resume')).fadeIn(900);
});
$("#CodingExamples1").click(function()
{
clearTheDisplay();
$(document.getElementById('AboutMe')).fadeIn(900);
});
});
I can't get the screen to clear with the two methods. Console doesn't recognize that the functions exist. I do get the fade in features to work though
I recommend just declaring the functions outside of the $(document).ready(function(){ .. });
The console doesn't recognize that the functions exist because you are basically trying to make local functions.
function clearTheDisplayInitial() {
$("#Resume, #CodingExamples, #AboutMe").hide();
}
function clearTheDisplay() {
$("#Resume, #CodingExamples, #AboutMe, #mainMenu").fadeOut(900);
}
$(document).ready(function() {
$("#displayResume").click(function() {
clearTheDisplayInitial(); // you could just add $("#Resume, #CodingExamples, #AboutMe").hide(); here
$("#Resume").fadeIn(900);
});
$("#CodingExamples1").click(function() {
clearTheDisplay(); // you could just add $("#Resume, #CodingExamples, #AboutMe, #mainMenu").fadeOut(900); here
$("#AboutMe").fadeIn(900);
});
});
I simplified your code by the way. I hope you didn't really need the functions to be inside of the document ready function.

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.

Categories

Resources