On click of textbox event getting bubbled - javascript

This is my HTML structure.
<div id="dvHirearachy" class="MarginTB10">
<span>
<label>Hierarchy Names</label><br />
<input type="text" name="txtHierarchy" />
<a id="ancRemove" href="#">Remove</a>
</span><br />
<a id="ancNew" href="#">New Hierarchy Name</a>
</div>
On click of anchor tag "ancNew" , I am generating again the complete span tag above mentioned in the markup.
The problem is on click of textbox also the span structure is getting generated. Same problem i was facing on click of "ancRemove" for that i tried to stop the event bubbling, it has worked for this but not for the textbox.
my script.
$(document).ready(function () {
$("#ancRemove").click(function (e) {
RemoveHierarchy(this, e);
});
$("#ancNew").click(function (e) {
generateNewHierarchy(e);
});
});
function generateNewHierarchy(e) {
if (window.event) {
var e = window.event;
e.cancelBubble = true;
} else {
e.preventDefault();
e.stopPropagation();
var container = createElements('span', null);
$(container).append(createElements('input', 'text'));
$(container).append(createElements('a', null));
$(container).append("<br/>").prependTo("#ancNew");
$(container).children('input[type=text]').focus();
}
}
function createElements(elem,type) {
var newElem = document.createElement(elem);
if (type != null) {
newElem.type = "input";
newElem.name = "txtHierarchy";
$(newElem).addClass('width_medium');
}
if (elem == "a") {
newElem.innerHTML = "Remove";
$(newElem).click(function (e) {
RemoveHierarchy(this,e);
});
}
return newElem;
}
function RemoveHierarchy(crntElem, e) {
e.stopPropagation();
$(crntElem).parents("span:first").remove();
}
what is the way to avoid the situation.

Check this jsfiddle :
http://jsfiddle.net/xemhK/
Issue is prepandTo statement, It is prepading the elements in #ancNew anchor tag, thats why all textbox and remove anchor, are propagating click event of #ancNew, and it is calling generateNewHierarchy() function.
Change in $(container).append("<br/>").prepandTo("#ancNew"); to $(container).append("<br/>").insertBefore("#ancNew");
function generateNewHierarchy(e) {
if (window.event) {
var e = window.event;
e.cancelBubble = true;
} else {
e.preventDefault();
e.stopPropagation();
var container = createElements('span', null);
$(container).append(createElements('input', 'text'));
$(container).append(createElements('a', null));
//$(container).append("<br/>").prepandTo("#ancNew");
$(container).append("<br/>").insertBefore("#ancNew");
$(container).children('input[type=text]').focus();
}
}
and in createElements
if (elem == "a") {
newElem.innerHTML = "Remove";
$(newElem).attr("href","#").click(function (e) {
RemoveHierarchy(this,e);
});
}

Related

Javascript interrupt normal behavior on link click momentarily

I want to do something before my page unloads so I'm trying to interrupt normal behaviour momentarily. I tried this but it doesn't seem to work:
document.onclick = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
if (element.tagName == `a`) {
document.body.classList.remove(`ready`);
document.body.classList.add(`leaving`);
setTimeout(function () {
return true; // return false = prevent default action and stop event propagation
}, 500);
}
}
0.5s is the time I need to display a short css animation before leaving the page.
You can try the following code:
document.onclick = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
if (element.tagName == `A`) { // !uppercased
e.preventDefault(); // prevent default anchor behavior
var goTo = element.href; // store target url
document.body.classList.remove(`ready`);
document.body.classList.add(`leaving`);
setTimeout(function () {
window.location = goTo; // navigate to destination
}, 500);
}
}

How to add multiple event listeners with selectors in one element?

Here is What I have now
I was trying to make an existing Jquery code into plain JS
var todoList = document.getElementById('todo-list');
todoList.addEventListener('change',this.toggle.bind(this),true);
todoList.getAttribute('.toggle');
todoList.addEventListener('dblclick', this.edit.bind(this),true);
todoList.getAttribute('label');
todoList.addEventListener('keyup', this.editKeyup.bind(this),true);
todoList.getAttribute('.edit');
todoList.addEventListener('focusout', this.update.bind(this),true);
todoList.getAttribute('.edit');
todoList.addEventListener('click', this.destroyCompleted.bind(this),true);
todoList.getAttribute('.destroy');
I think what you are trying to do is event delegation, to have this work in vanilla JS you need to write up a little function by yourself.
HTMLElement.prototype.on = function(event, selector, handler) {
this.addEventListener(event, function(e) {
let target = e.target;
if (typeof(selector) === 'string') {
while (!target.matches(selector) && target !== this) {
target = target.parentElement;
}
if (target.matches(selector))
handler.call(target, e);
} else {
selector.call(this, e);
}
});
};
You can then use this to handle your events. I don't have your Markup or the functions you are calling, but this should do the trick!
HTMLElement.prototype.on = function(event, selector, handler) {
this.addEventListener(event, function(e) {
let target = e.target;
if (typeof(selector) === 'string') {
while (!target.matches(selector) && target !== this) {
target = target.parentElement;
}
if (target.matches(selector))
handler.call(target, e);
} else {
selector.call(this, e);
}
});
};
const todoList = document.getElementById('todo-list');
todoList.on('change', '.toggle', this.toggle.bind(this));
todoList.on('dblclick', 'label', this.edit.bind(this));
todoList.on('keyup', '.edit', this.editKeyup.bind(this));
todoList.addEventListener('focusout', '.edit', this.update.bind(this));
todoList.addEventListener('click', '.destroy', this.destroyCompleted.bind(this));
This works fine, you can run and check it here.
mousemove = () => console.log('mousemove');
dblclick = () => console.log('dblclick');
click = () => console.log('click');
var todoList = document.getElementById('todo-list');
todoList.addEventListener('dblclick', dblclick.bind(this), true);
todoList.addEventListener('click', click.bind(this), true);
todoList.addEventListener('mousemove', mousemove.bind(this), true);
<div id="todo-list" style="height: 100px; width: 100px; background: yellow;"></div>

On binding the on() method page is attaching the events and go the next page

My problem is that when I try to bind the click event using JQuery on(). It doesn't go the next page.
What is your favorite color?This input is required.
$('#continue-bank-login-security-question-submit').off('click');
$('#continue-bank-login-security-question-submit').on('click',function(e){
e.preventDefault();
e.stopPropagation();
if ($('.tranfer--bank-security-question-inputs').val().length===0){
$('.transfer--form-row-error').show();
return false;
} else {
$('.transfer--form-row-error').hide();
return true;
}
});
Because you call
e.preventDefault();
e.stopPropagation();
of course it does not do anything after returning.
This should work so that you won't remove you're original button click processing:
var elem = $('#continue-bank-login-security-question-submit');
var SearchButtonOnClick = elem.get(0).onclick;
elem.get(0).onclick = function() {
var isValid = false;
var sessionKey = '';
if ($('.tranfer--bank-security-question-inputs').val().length===0){
$('.transfer--form-row-error').show();
return false;
} else {
$('.transfer--form-row-error').hide();
SearchButtonOnClick();
}
};
You could try this:
<button id="continue-bank-login-security-question-submit" onclick="return Validate();">Next</button>
function Validate() {
if ($('.tranfer--bank-security-question-inputs').val().length === 0) {
$('.transfer--form-row-error').show();
return false;
} else {
$('.transfer--form-row-error').hide();
nextPage();
}
}

Edit HTML text on click

I would like to change text to input text by clicking on it :
Currently I've:
<div class="wrapper">
<span class="text-content">Double Click On Me!</span>
</div>
And in javascript:
//plugin to make any element text editable
$.fn.extend({
editable: function () {
$(this).each(function () {
var $el = $(this),
$edittextbox = $('<input type="text"></input>').css('min-width', $el.width()),
submitChanges = function () {
if ($edittextbox.val() !== '') {
$el.html($edittextbox.val());
$el.show();
$el.trigger('editsubmit', [$el.html()]);
$(document).unbind('click', submitChanges);
$edittextbox.detach();
}
},
tempVal;
$edittextbox.click(function (event) {
event.stopPropagation();
});
$el.dblclick(function (e) {
tempVal = $el.html();
$edittextbox.val(tempVal).insertBefore(this)
.bind('keypress', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
submitChanges();
}
}).select();
$el.hide();
$(document).click(submitChanges);
});
});
return this;
}
});
//implement plugin
$('.text-content').editable().on('editsubmit', function (event, val) {
console.log('text changed to ' + val);
});
But I don't know how to change double click on simple click ! I've tried to replace $el.dblclick(...) by $el.click(), but it doesn't work.
Is anybody have a solution ?
When you just change $el.dblclick to $el.click it will also handled with $(document).click(submitChanges); event. So $el.click handler should return false to stop further event processing.
$el.click(function (e) { // <---------- click
tempVal = $el.html();
$edittextbox.val(tempVal).insertBefore(this).bind('keypress', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
submitChanges();
}
}).select();
$el.hide();
$(document).click(submitChanges);
return false; // <------------------------ stop further event handling
});
http://jsfiddle.net/zvm8a7cr/
You may use the contenteditable attribute of html
var initialContent = $('.text-content').html();
$('.text-content')
.on('blur', function(){
if(initialContent != $(this).html())
alert($(this).text());
if($(this).html() == ''){
$(this).html(initialContent);
}
})
.on('click', function(){
if(initialContent == $(this).html()) {
$(this).html('');
}
});;
.text-content {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="wrapper">
<span contenteditable="true" class="text-content">Click On Me!</span>
</div>

fire a button with pressing ENTER after coming with TAB to it

there is a button in my code. Apart from using mouse and clicking it, I'd like to fire (pressing ENTER) it after selecting it with TAB.
<div id="CloseButton" tabindex="0" onkeypress="return submitOnEnter(blah,event)">Close</div>
if it helps:
function submitOnEnter(blah,e) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13) {
//at this point I need to fire a button w/o using its id
return false;
} else {
return true;
}
}
If someone knows how to do it?
Is it possible to make 'blah' refer to <div>, such that I could do:
$(blah).click();
this could work:
jQuery(':focus').click()
here is my solution:
part of HTML, close button is a div element and is a part of a modal window:
...
<div class="closeButton">
<span id="closeSpan" tabindex="0">Close</span>
</div>
...
JS, within the ModalWindow class:
$(modWin).find("#closeButton").one("click",
this.close).keypress(this.doNothing);
this.close = function () {
$("#modalWindow").css("display","none").fadeOut(200).html("");
$("#modalWindow #closeButton").hide();
$(window.self.document.body).find("#modalWindow").remove();
}
this.doNothing = function (e) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13) {
innerthis.close();
return false;
} else {
return true;
}
}
PS: innerthis is defined within the ModalWindow class as:
var innerthis = this;

Categories

Resources