use of isDefaultPrevented() with custom events - javascript

Hey guys i was just going through the carasoul.js code and came across the following lines of code :
if (slideEvent.isDefaultPrevented()) return
now the documentation of isDefaultPrevented() gives the foolowing example :
$( "a" ).click(function( event ) {
alert( event.isDefaultPrevented() ); // false
event.preventDefault();
alert( event.isDefaultPrevented() ); // true
});
but i am not attaching a click event so how is isDefaultPrevented of any assists here ? , the entire function code can be seen below ::
Carousel.prototype.slide = function (type, next) {
var $active = this.$element.find('.item.active')
var $next = next || this.getItemForDirection(type, $active)
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var that = this
if ($next.hasClass('active')) return (this.sliding = false)
var relatedTarget = $next[0]
var slideEvent = $.Event('slide.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
})
this.$element.trigger(slideEvent)
if (slideEvent.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
$nextIndicator && $nextIndicator.addClass('active')
}
var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one('bsTransitionEnd', function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () {
that.$element.trigger(slidEvent)
}, 0)
})
.emulateTransitionEnd(Carousel.TRANSITION_DURATION)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger(slidEvent)
}
isCycling && this.cycle()
return this
}
Why the use of isDefaultPrevented() ?

The Bootstrap carousel triggers events at interesting moments, for example before and after it slides. If you want to do something when these events happen, you can react to them like so:
$('.carousel').on('slide.bs.carousel', function (e) {
// do something before a carousel slides
});
And if you want to prevent the carousel from it's default behaviour, you can do that like so:
$('.carousel').on('slide.bs.carousel', function (e) {
// prevent the carousel from sliding
e.preventDefault();
});
Bootstrap then checks if an event handler called preventDefault() and stops its default behaviour if it happened:
if (slideEvent.isDefaultPrevented()) return

Related

manage multiple messages from content-script to a vue js popup page in google-chrome-extension [duplicate]

Hello i am learning vuejs and was converting one of my projects into vuejs i wanted to know that i can write my custom functions in methods and call those in mounted hook i wanted to know how do i use listeners in vuejs.
also can i used my jquery by importing in vue project
The event listener documentation on vue website states only v-on and click example but no examples are for windows listeners
jQuery(document).ready(function(){
//cache DOM elements
var mainContent = $('.cd-main-content'),
header = $('.cd-main-header'),
sidebar = $('.cd-side-nav'),
sidebarTrigger = $('.cd-nav-trigger'),
topNavigation = $('.cd-top-nav'),
searchForm = $('.cd-search'),
accountInfo = $('.account');
//on resize, move search and top nav position according to window width
var resizing = false;
moveNavigation();
$(window).on('resize', function(){
if( !resizing ) {
(!window.requestAnimationFrame) ? setTimeout(moveNavigation, 300) : window.requestAnimationFrame(moveNavigation);
resizing = true;
}
});
//on window scrolling - fix sidebar nav
var scrolling = false;
checkScrollbarPosition();
$(window).on('scroll', function(){
if( !scrolling ) {
(!window.requestAnimationFrame) ? setTimeout(checkScrollbarPosition, 300) : window.requestAnimationFrame(checkScrollbarPosition);
scrolling = true;
}
});
//mobile only - open sidebar when user clicks the hamburger menu
sidebarTrigger.on('click', function(event){
event.preventDefault();
$([sidebar, sidebarTrigger]).toggleClass('nav-is-visible');
});
//click on item and show submenu
$('.has-children > a').on('click', function(event){
var mq = checkMQ(),
selectedItem = $(this);
if( mq == 'mobile' || mq == 'tablet' ) {
event.preventDefault();
if( selectedItem.parent('li').hasClass('selected')) {
selectedItem.parent('li').removeClass('selected');
} else {
sidebar.find('.has-children.selected').removeClass('selected');
accountInfo.removeClass('selected');
selectedItem.parent('li').addClass('selected');
}
}
});
//click on account and show submenu - desktop version only
accountInfo.children('a').on('click', function(event){
var mq = checkMQ(),
selectedItem = $(this);
if( mq == 'desktop') {
event.preventDefault();
accountInfo.toggleClass('selected');
sidebar.find('.has-children.selected').removeClass('selected');
}
});
$(document).on('click', function(event){
if( !$(event.target).is('.has-children a') ) {
sidebar.find('.has-children.selected').removeClass('selected');
accountInfo.removeClass('selected');
}
});
//on desktop - differentiate between a user trying to hover over a dropdown item vs trying to navigate into a submenu's contents
sidebar.children('ul').menuAim({
activate: function(row) {
$(row).addClass('hover');
},
deactivate: function(row) {
$(row).removeClass('hover');
},
exitMenu: function() {
sidebar.find('.hover').removeClass('hover');
return true;
},
submenuSelector: ".has-children",
});
function checkMQ() {
//check if mobile or desktop device
return window.getComputedStyle(document.querySelector('.cd-main-content'), '::before').getPropertyValue('content').replace(/'/g, "").replace(/"/g, "");
}
function moveNavigation(){
var mq = checkMQ();
if ( mq == 'mobile' && topNavigation.parents('.cd-side-nav').length == 0 ) {
detachElements();
topNavigation.appendTo(sidebar);
searchForm.removeClass('is-hidden').prependTo(sidebar);
} else if ( ( mq == 'tablet' || mq == 'desktop') && topNavigation.parents('.cd-side-nav').length > 0 ) {
detachElements();
searchForm.insertAfter(header.find('.cd-logo'));
topNavigation.appendTo(header.find('.cd-nav'));
}
checkSelected(mq);
resizing = false;
}
function detachElements() {
topNavigation.detach();
searchForm.detach();
}
function checkSelected(mq) {
//on desktop, remove selected class from items selected on mobile/tablet version
if( mq == 'desktop' ) $('.has-children.selected').removeClass('selected');
}
function checkScrollbarPosition() {
var mq = checkMQ();
if( mq != 'mobile' ) {
var sidebarHeight = sidebar.outerHeight(),
windowHeight = $(window).height(),
mainContentHeight = mainContent.outerHeight(),
scrollTop = $(window).scrollTop();
( ( scrollTop + windowHeight > sidebarHeight ) && ( mainContentHeight - sidebarHeight != 0 ) ) ? sidebar.addClass('is-fixed').css('bottom', 0) : sidebar.removeClass('is-fixed').attr('style', '');
}
scrolling = false;
}
});
You can listen for a window event in Vue like this:
methods: {
onResize(event) {
console.log('window has been resized', event)
}
},
mounted() {
// Register an event listener when the Vue component is ready
window.addEventListener('resize', this.onResize)
},
beforeDestroy() {
// Unregister the event listener before destroying this Vue instance
window.removeEventListener('resize', this.onResize)
}
You will have to add the listeners for your events in created hook.
For example:
window.addEventListener('scroll', this.handleScroll);
You can add your logic in handleScroll method next.
Note: Don't forget to remove listener on destroyed hook!

What is the simplest way of marking my "To-do" as complete?

I have a fiddle here: https://jsfiddle.net/419r62t8/1/
View.prototype.render = function (viewCmd, parameter) {
var that = this;
var viewCommands = {
showEntries: function () {
that.$todoList.innerHTML = that.template.show(parameter);
},
removeItem: function () {
that._removeItem(parameter);
},
updateElementCount: function () {
that.$todoItemCounter.innerHTML = that.template.itemCounter(parameter);
},
contentBlockVisibility: function () {
that.$main.style.display = that.$footer.style.display = parameter.visible ? 'block' : 'none';
},
setFilter: function () {
that._setFilter(parameter);
},
clearNewTodo: function () {
that.$newTodo.value = '';
},
editItem: function () {
that._editItem(parameter.id, parameter.title);
},
editItemDone: function () {
that._editItemDone(parameter.id, parameter.title);
}
};
viewCommands[viewCmd]();
};
View.prototype._itemId = function (element) {
var li = $parent(element, 'li');
return parseInt(li.dataset.id, 10);
};
View.prototype._bindItemEditDone = function (handler) {
var that = this;
$live('#todo-list li .edit', 'blur', function () {
if (!this.dataset.iscanceled) {
handler({
id: that._itemId(this),
title: this.value
});
}
});
$live('#todo-list li .edit', 'keypress', function (event) {
if (event.keyCode === that.ENTER_KEY) {
// Remove the cursor from the input when you hit enter just like if it
// were a real form
this.blur();
}
});
};
View.prototype._bindItemEditCancel = function (handler) {
var that = this;
$live('#todo-list li .edit', 'keyup', function (event) {
if (event.keyCode === that.ESCAPE_KEY) {
this.dataset.iscanceled = true;
this.blur();
handler({id: that._itemId(this)});
}
});
};
View.prototype.bind = function (event, handler) {
var that = this;
if (event === 'newTodo') {
$on(that.$newTodo, 'change', function () {
handler(that.$newTodo.value);
});
} else if (event === 'itemEdit') {
$live('#todo-list li label', 'dblclick', function () {
handler({id: that._itemId(this)});
});
} else if (event === 'itemRemove') {
$live('#todo-list .destroy', 'click', function () {
handler({id: that._itemId(this)});
});
} else if (event === 'itemEditDone') {
that._bindItemEditDone(handler);
} else if (event === 'itemEditCancel') {
that._bindItemEditCancel(handler);
} else if (even === 'itemComplete') {
that._bindItemComplete(handler);
}
};
EDIT: I am thinking I can bind a new function here to add an strike-through to the "completed" items on the todo list. Completing them on single click or by adding a checkbox for completing it.
I've got the CSS but I'm lacking the JS to tie it all together.
I am attempting to create a simple strike through on-click to show when an item has been marked as completed. Any help would be much appreciated.
You're close with the CSS, but the best bet is to replace the checkbox with an image (svg if you can) when it is checked.
text-decoration: line-through will not help here -- this only works with text.
Often the checkbox's label will get the image and the checkbox itself will be hidden (a label can be clicked and perform the same actions as the input/checkbox itself)
Check this Answer out and see if it'll help you along your path:
Pure CSS Checkbox Image replacement
Try adding a jquery event listener to the id of the checkbox. Tell id to toggle the css on click and you should be good to go. Do you know how to achieve that?

Jquery: <a> link click preventDefault() not working?

I'm trying to prevent a link click from firing if accidentally touched while scrolling in mobile? I have never tried something like this before and am having trouble getting it to work right. I am testing this on a desktop for the time being.
My buttons are structured similar to:
<a href="http://www.google.com">
<div style="width:100%;height:80px;margin-bottom:50px;">test</div>
</a>
I am trying to use the preventDefault() function to override default click actions and check if a the page is being scrolled, or it the click was accidental before allowing it to work. The logic to check seems to work, however the links navigate on click no matter what i do. I assume this has something to do with the links behaviour being propogated to the child div, but am not sure.
Below is my script, the problem is in the last $('a').click(); function.
UPDATE:
I still need a better way to do it using just the $('a') selector if anyone knows how. Kind of a hack but, if i change the selector to $('a>div') and change the 'targetLink' to $(this).parent().attr('href') it seems to work, Is there a way to do this using $('a') only because some of my buttons have more children.
//Mobile accidental scroll click fix:---
//- prevent clicked link from executing if user scrolls after mousedown, until next mousedown.
//- prevent clicked link from executing if user is still scrolling and mouse is down(for slow scrolls)
$(document).ready(function(){
var self = this,
scrolling = false,
mouseDown = false,
scrollAfterPress = false;
scrollDelay = 1500,
linkConditionCheckDelay = 700;
$(window).scroll(function() {
self.scrolling = true;
console.log('scrolling:' + self.scrolling);
clearTimeout( $.data( this, "scrollCheck" ) );
$.data( this, "scrollCheck", setTimeout(function() {
self.scrolling = false;
console.log('scrolling:' + self.scrolling);
}, scrollDelay) );
});
$(document).mousedown(function(){
self.scrollAfterPress = false;
int00 = setInterval(function() { checkScrollAfterPress(); }, 100);//execute every 100ms (while mouse is down)
self.mouseDown = true;
console.log('mousedown:'+ self.mouseDown);
}).mouseup(function(){
clearInterval(int00);
self.mouseDown = false;
console.log('mousedown:'+ self.mouseDown);
});
function checkScrollAfterPress(){
if(self.scroll === true){
self.scrollAfterPress = true;
}
}
$('a').click(function(e){
//prevent default click event behaviour
var targetLink = $(this).attr('href');
console.log('clicked on:'+targetLink);
setTimeout(function() {
if(!self.scrolling && !self.mouseDown && !self.scrollAfterPress && targetLink !== undefined){
window.location.href = targetLink;
}
}, linkConditionCheckDelay); //add small delay to prevent immeditiate responses between mouse up and start of scroll.
e.stopPropagation();
e.preventDefault();
});
});
You can use return false or e.preventDefault
But when you click on that link why your adding window.location.href = targetLink;?? which will redirect the user to the given location.Same as link
Try my code below i have removed it.
$(document).ready(function(){
var self = this,
scrolling = false,
mouseDown = false,
scrollAfterPress = false;
scrollDelay = 1500,
linkConditionCheckDelay = 700;
$(window).scroll(function() {
self.scrolling = true;
console.log('scrolling:' + self.scrolling);
clearTimeout( $.data( this, "scrollCheck" ) );
$.data( this, "scrollCheck", setTimeout(function() {
self.scrolling = false;
console.log('scrolling:' + self.scrolling);
}, scrollDelay) );
});
$(document).mousedown(function(){
self.scrollAfterPress = false;
int00 = setInterval(function() { checkScrollAfterPress(); }, 100);//execute every 100ms (while mouse is down)
self.mouseDown = true;
console.log('mousedown:'+ self.mouseDown);
}).mouseup(function(){
clearInterval(int00);
self.mouseDown = false;
console.log('mousedown:'+ self.mouseDown);
});
function checkScrollAfterPress(){
if(self.scroll === true){
self.scrollAfterPress = true;
}
}
$('a').click(function(e){
//prevent default click event behaviour
var targetLink = $(this).attr('href');
console.log('clicked on:'+targetLink);
setTimeout(function() {
if(!self.scrolling && !self.mouseDown && !self.scrollAfterPress && targetLink !== undefined){
//window.location.href = targetLink;
}
}, linkConditionCheckDelay); //add small delay to prevent immeditiate responses between mouse up and start of scroll.
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://www.google.com">
<div style="width:100%;height:80px;margin-bottom:50px;">test</div>
</a>
I will suggest another approach and use jQuery Mobile Events. Something like this:
*untested, but is the idea
// set global var 'locked'
var locked = false;
// locked var true while scrolling
jQuery(document).on('scrollstart', function() { locked = true; });
// locked var back to false when finish
jQuery(document).on('scrollstop', function() { locked = false; });
// bind 'tap' & 'click' events to 'a' tag
jQuery(document).on('tap click', 'a', function(event) {
// But before proceed, check locked var
if (locked) {
event.preventDefault;
return false;
} else {
// ok, proceed with the click and further events...
}
});
Docs/ref:
scrollstart event
scrollstop event
tap event
vclick event
.click()
Use in your $'a'.click(function(e){...} part return false; to prevent the default behavior.
In your case:
$('a').click(function(e){
var targetLink = $(this).attr('href');
console.log('clicked on:'+targetLink);
setTimeout(function() {
if(!self.scrolling && !self.mouseDown && !self.scrollAfterPress && targetLink !== undefined){
window.location.href = targetLink;
}
}, linkConditionCheckDelay);
return false;//Stops default behavior
});
Perhaps there is something I am missing, but I do not see why your code cannot be made as simple as the following:
$(document).ready(function () {
var is_scrolling = false;
var timeout = null;
$(window).scroll(function () {
is_scrolling = true;
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function () {
is_scrolling = false;
}, 1500);
});
$('a').click(function (e){
if (is_scrolling) {
e.preventDefault();
}
});
});

How to cancel single click event when double click event uses

I am using asp .net mvc 4. My problem is in my modal popup I am using mouse double click. It works properly, but if I cancel particular popup form and then single click on details, again it will displays. The main problem is that single works as the double click. I need some time delay between these clicks. I only need to display modal popup with double click. If I submit the details may be of page refreshing it get works. Below shown is modal.js that I make changes.(only change click to dblclick)
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.escape()
**this.$element.on('click.dismiss.modal', '[data-dismiss="modal"]',** $.proxy(this.hide, this))
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.attr('aria-hidden', true)
.off('click.dismiss.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one($.support.transition.end, $.proxy(this.hideModal, this))
.emulateTransitionEnd(300) :
this.hideModal()
}
this.$element.on('click.dismiss.modal', $.proxy(function (e) {
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus.call(this.$element[0])
: this.hide.call(this)
}, this))
$(document).on('dblclick.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
//alert("onclick");
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
var option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
e.preventDefault()
$target
.modal(option, this)
.one('hide', function () {
$this.is(':visible') && $this.focus()
})
})
in my candidate.js
$('body').on('dblclick', '.IndMaster-edit', function (e) {
//alert("succ111");
e.preventDefault();
//alert($(this).attr('class'));
$(this).attr('data-target', '#modal-container');
$(this).attr('data-toggle', 'modal');
});
$(".IndMaster-edit").dblclick(function () {
//alert("first");
var sectionvalue = $(this).attr("data-id");
var titleselection = $(this).attr("title");
//alert(titleselection);
//alert(sectionvalue.toString());
$.ajax({
async:false,
// Call CreatePartialView action method
url: "/IndMaster/EditIndPartial",
data: { section: sectionvalue, indmanid: titleselection },
type: 'Get',
success: function (data) {
//alert("hhiii");
//$('#myModal').modal('show');
$("#IndMaster-DetailModel").empty();
//alert("end1");
//alert("success11");
$("#IndMaster-DetailModel").append(data);
//alert("end2");
//alert("success22");
$("#IndMaster-DetailModel").dialog("open");
//$("#createForm").hide();
//alert("end3");
//alert("success");
},
error: function () {
alert("something seems wrong");
}
});
});
In my IndMaster.cshtml
<td class="tagstd IndMaster-edit" data-id="status" title="#item.Ind_ID">
<span class="btn btn-xs icon-tag pull-left tag-btn" data-id="Package_No" title="#item.Ind_ID" style="visibility:hidden"></span> #item.IND_APP_PASS_STATUS.First().Package_No</td>
I changed click function to dblclick.
I created a jsfiddle for this, please check, using this you have to use a delay so that you can count the number of clicks
var DELAY = 700, clicks = 0, timer = null;
$(function(){
$("a").on("click", function(e){
clicks++; //count clicks
if(clicks === 1) {
timer = setTimeout(function() {
alert("Single Click"); //perform single-click action
clicks = 0; //after action performed, reset counter
}, DELAY);
} else {
clearTimeout(timer); //prevent single-click action
alert("Double Click"); //perform double-click action
clicks = 0; //after action performed, reset counter
}
})
.on("dblclick", function(e){
e.preventDefault(); //cancel system double-click event
});
});
http://jsfiddle.net/y7epojfo/

Is there a better way to code this in JavaScript and/or jQuery?

Here it is:
//Disable KeyboardNavigation
document.getElementById("author").onfocus = function() {
document.onkeyup = null;
};
document.getElementById("email").onfocus = function() {
document.onkeyup = null;
};
document.getElementById("url").onfocus = function() {
document.onkeyup = null;
};
document.getElementById("comment").onfocus = function() {
document.onkeyup = null;
};
//Enable KeyboardNavigation
document.getElementById("author").onblur = function() {
document.onkeyup = KeyCheck;
};
document.getElementById("email").onblur = function() {
document.onkeyup = KeyCheck;
};
document.getElementById("url").onblur = function() {
document.onkeyup = KeyCheck;
};
document.getElementById("comment").onblur = function() {
document.onkeyup = KeyCheck;
};
I believe it's definitely possible to write a better code with a loop but I really don't know how to make it work. I tried the following:
var formfields= ["author", "email", "url", "comment"];
for (i=1; i<=3; i++){
//Don't really know what to put in here.
}
Thank you in advance for your help!
EDIT : Whole code is below. You should know that I got some help to get to this result:
document.onkeyup = KeyCheck;
var pages = [
"http://",
"http://",
"http://",
"http://",
"http://"];
function leftarrowpressed() {
location.href = pages[ Math.max(0, 0 - 1) ];
//The second '0' here changes from 0 to 4, according to the page.
}
function rightarrowpressed() {
location.href = pages[ Math.min(pages.length - 1, 0 + 1) ];
//The second '0' here changes from 0 to 4, according to the page.
}
function KeyCheck(e)
{
var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch(KeyID)
{
// left arrow key
case 37:
leftarrowpressed();
break;
// right arrow key
case 39:
rightarrowpressed();
break;
}
}
Hope this can help a little more. By the way, thank you everyone. I really don't know which solution to choose.
It looks like what you are doing is trying to prevent keystrokes in an input element from affecting navigation. What you could do instead is check event.target in KeyCheck and only perform the action if it was not triggered by an input element.
function KeyCheck(e) {
var target = e ? e.target : event.srcElement, //standards vs IE
tagname = target.tagName.toLowerCase();
if( tagname !== "input" && tagname !== "textarea" && tagname !== "select") {
//Not from an input, NAVIGATE!
}
}
If using jQuery then you can go a more straight-forward way: inside KeyCheck, check whether any of the elements is focused, and don't do anything in that case. You won't need any of the above.
function KeyCheck(e) {
if($("#author, #email, #url, #comment").is(":focus")) {
return; // ignore if any of these elements has focus
}
// ...
}
Make sure to bind KeyCheck using jQuery too:
$("body").on("keyup", KeyCheck);
var formfields= ["author", "email", "url", "comment"];
for (i=0; i<=3; i++){
var field = document.getElementById(formFields[i]);
field.onfocus = function() {
document.onkeyup = null;
};
field.onblur = function() {
document.onkeyup = KeyCheck;
};
}
or more proper way would be to use something like this
jQuery.each("author email url comment".split(" "), function(i, name) {
$('#' + name).focus(function() {
// do whatever you want to do
}).blur(function() {
// do whatever you wnat to do
));
});
Neat and readable:
var formfields = ["author", "email", "url", "comment"],
i, elem,
blur = function() { document.onkeyup = KeyCheck; },
focus = function() { document.onkeyup = null; };
for (i=0; i<=3; i++) {
elem = document.getElementById(formFields[i]);
elem.onblur = blur;
elem.onfocus = focus;
}
look for the nearest common parent for these elements and add a handler to it. we can use the powers of delegation using the .on() as well as method chaining to bind a hander only to the parent (in this case, 2 handlers for all, not 8 where 2 per element) to take effect on all 4 elements.
var selectors = '#author, #email, #url, #comment';
$('nearest_parent_element').on('focus', selectors, function() {
document.onkeyup = null;
}).on('blur', selectors, function() {
document.onkeyup = KeyCheck;
});​
jQuery way:
$("#author, #email, #url, #comment").on({
focus: function() {
$(document).on('keyup', null);
},
blur: function() {
$(document).on('keyup', KeyCheck);
}
});
It all depends on how good you are at JavaScript. I would recommend for you to use event delegation: http://jsfiddle.net/teresko/PkCuZ/3/
It might look a bit complicated , but the add_listener() function would be shared throughout the whole code , so the payload actually looks like this:
var handlers = {
keyout: function(e){
var event = e || window.event,
target = event.target || event.srcElement;
console.log( 'leaving ' + target.name );
},
keyin: function(e){
var event = e || window.event,
target = event.target || event.srcElement;
console.log( 'entering ' + target.name );
}
},
container = document.getElementById('container');
add_listener( container, 'blur' , handlers.keyout );
add_listener( container, 'focus' , handlers.keyin );
This would work with any number of form elements.
As for the add_listener() function , it contains a small fix for blur/focus on IE, and a per-application choice of which method of attaching events to use. It's kinda an universal function which you can just drop in, when you need a common interface for attaching listeners:
var add_listener = (function () {
var fix = {
'focus': 'focusin',
'blur': 'focusout'
};
if ( window.addEventListener ) {
return function ( element, type, callback ) {
element.addEventListener(type, callback, typeof(fix[type]) !== undefined );
};
}else{
return function ( element, type, callback ) {
type = fix[type] || type;
element.attachEvent('on' + type, callback);
};
}
})();

Categories