How can I create a custom event using jquery - javascript

I want to create an event when the content of a div changes, the event is called..
change = function(oldval,newval){
if (oldval != newval){
return true;
}
return false;
}
I want this function to be called everytime the content of a div changes ..Any idea how i can achieve this ?

I want this function to be called everytime the content of an element changes
If the content of an element equals to the value of form inputs:
One line code:
$(':input', $('#divId')).change(function(){alert('changed');});
Or the delegate option for dynamic added elements (still one line... (; ):
$('#divId').on('change', ':input', function(){ alert('changed');});
docs:
on
:input selector

If you arent planning on supporting IE you can use DOMNodeInserted and DOMNodeRemoved to check if elements are added or removed from your div.
$('#yourDiv').bind('DOMNodeInserted DOMNodeRemoved', function(event, oldvalue, newvalue) {
if (oldval != newval){
return true;
}
return false;
});
for IE support you can use
$(function() {
var $div = $("#yourDiv");
var content = $div.html();
var look = setInterval(function() {
var newcontent = $div.html();
if (html != newcontent ) {
change(content, newcontent);
content = newcontent;
}
},100);
function change(oldval, newval() {
if (oldval != newval){
return true;
}
return false;
}
});

Related

JS - Add class to form when input has value

I have a form with one input field for the emailaddress. Now I want to add a class to the <form> when the input has value, but I can't figure out how to do that.
I'm using this code to add a class to the label when the input has value, but I can't make it work for the also:
function checkForInputFooter(element) {
const $label = $(element).siblings('.raven-field-label');
if ($(element).val().length > 0) {
$label.addClass('input-has-value');
} else {
$label.removeClass('input-has-value');
}
}
// The lines below are executed on page load
$('input.raven-field').each(function() {
checkForInputFooter(this);
});
// The lines below (inside) are executed on change & keyup
$('input.raven-field').on('change keyup', function() {
checkForInputFooter(this);
});
Pen: https://codepen.io/mdia/pen/gOrOWMN
This is the solution using jQuery:
function checkForInputFooter(element) {
// element is passed to the function ^
const $label = $(element).siblings('.raven-field-label');
var $element = $(element);
if ($element.val().length > 0) {
$label.addClass('input-has-value');
$element.closest('form').addClass('input-has-value');
} else {
$label.removeClass('input-has-value');
$element.closest('form').removeClass('input-has-value');
}
}
// The lines below are executed on page load
$('input.raven-field').each(function() {
checkForInputFooter(this);
});
// The lines below (inside) are executed on change & keyup
$('input.raven-field').on('change keyup', function() {
checkForInputFooter(this);
});
I've updated your pen here.
Here it is, using javascript vanilla. I selected the label tag ad form tag and added/removed the class accoring to the element value, but first you should add id="myForm" to your form html tag. Good luck.
function checkForInputFooter(element) {
// element is passed to the function ^
let label = element.parentNode.querySelector('.raven-field-label');
let myForm = document.getElementById("myform");
let inputValue = element.value;
if(inputValue != "" && inputValue != null){
label.classList.add('input-has-value');
myForm.classList.add('input-has-value');
}
else{
label.classList.remove('input-has-value');
myForm.classList.remove('input-has-value');
}
}
You can listen to the 'input' event of the input element and use .closest(<selector>) to add or remove the class
$('input').on('input', function () {
if (!this.value) {
$(this).closest('form').removeClass('has-value');
} else {
$(this).closest('form').addClass('has-value');
}
})
Edit: https://codepen.io/KlumperN/pen/xxVxdzy

Trying to invoke onchange method set by jQuery

In my code, I am setting a change listener on my checkboxes here
$(".section").change(function() {
if($(this).is(":checked")) {
$("." + this.id).show();
...
Now I am trying to do a "code-driven" click on the checkbox, and I have
$(".secTitle").click(function(e) {
var elem = this;
while(elem) {
if (elem.className && elem.className.indexOf ('DOC_SECTION') != -1) {
var clzes = elem.className.split(" ");
var clzIdx = 1;
if (elem.getAttribute('closeSecClassIdx')) {
clzIdx = parseInt(elem.getAttribute('closeSecClassIdx'));
}
var chk = document.getElementById(clzes[clzIdx]);
chk.checked = false;
alert(chk.onchange);
//chk.changed();
break;
}
else {
elem = elem.parentNode;
}
}
});
I know that I have the right element, as chk.checked = false; is working correctly. After that I'm trying to invoke the change method set earlier but my alert is showing 'undefined'.
You can trigger the change event by calling $(chk).change(). Below I've created a little prototype that shows binding to the change event and invoking it.
jQuery(function($) {
// bind to the change event
$("input").change(function() {
console.log('change triggered!');
});
// now trigger it
$("input").change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />

jquery clone not working if user select other from the drop down the current text field disabled false

Working on jquery clone with my current code everthing works fine.
first scenario if user select other from the drop down the text
field gets enabled
Second scenario if user click addmore button div gets clone
perfectly with id when user select other both Original and clone
textfield gets enabled actually it should be only the cloned should
get enabled not the enabled
Here is the current Jquery code
var i=1;
$(document).on("click", ".edu_add_button", function () {
var i=$('.cloned-row1').length;
$(".cloned-row1:last").clone(true).insertAfter(".cloned-row1:last").attr({
'id': function(_, id) { return id + i },
'name': function(_, name) { return name + i }
}).end().find('[id]').val('').attr({ 'id': function(_, id) { return id + i }
});
$(".cloned-row1:last").find(".school_Name").attr('disabled', true).val('');
if(i < $('.cloned-row1').length){
$(this).closest(".edu_add_button").removeClass('btn_more edu_add_button').addClass('btn_less btn_less1');
}
i++;
return false;
});
$(document).on('click', ".btn_less1", function (){
var len = $('.cloned-row1').length;
if(len>1){
$(this).closest(".cloned-row1").remove();
}
});
$(document).on('change', '.txt_schName', function (){
var cur = $('.txt_schName').index($(this));
$('.school_Name').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$(".school_Name").prop('disabled', false);
$(".school_Name").val('');
}else{
$(".school_Name").prop('disabled', true);
}
});
$(document).on('change', '.txt_degreName', function (){
var cur = $('.txt_degreName').index($(this));
$('.degree_Description').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$("#degree_Description").prop('disabled', false);
$("#degree_Description").val('');
}else{
$("#degree_Description").prop('disabled', true);
}
});
Here is the fiddle link
Kindly suggest me
thanks & regards
Mahadevan
DEMO
The issue comes be cause you are using class selector directly. You need apply value only to the text box which belongs in the same container. Use closest() to find the parent.
$(document).on('change', '.txt_schName', function (){
var cur = $('.txt_schName').index($(this));
var container = $(this).closest('.container-fluid');
$('.school_Name').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$(".school_Name", container).prop('disabled', false);
$(".school_Name", container).val('');
}else{
$(".school_Name", container).prop('disabled', true);
}
});
DEMO HERE
You need to refer proper element that has to be disabled and enabled.
Take the sibling of select's parent and find the input element to be disabled as below:
$(document).on('change', '.txt_schName', function (){
var cur = $('.txt_schName').index($(this));
$(this).closest('.col-xs-6').next('.col-xs-6').find('.school_Name').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$(this).closest('.col-xs-6').next('.col-xs-6').find(".school_Name").prop('disabled', false);
$(this).closest('.col-xs-6').next('.col-xs-6').find(".school_Name").val('');
}else{
$(this).closest('.col-xs-6').next('.col-xs-6').find(".school_Name").prop('disabled', true);
}
});
From what you did, you actually change every fields with class .school_Name, to achieve what you want you can add $(this).parents(".row").find(".class_name") so it only change the current div.
$(document).on('change', '.txt_schName', function (){
var cur = $('.txt_schName').index($(this));
$('.school_Name').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$(this).parents(".row").find(".school_Name").prop('disabled', false);
$(this).parents(".row").find(".school_Name").val('');
}else{
$(this).parents(".row").find(".school_Name").prop('disabled', true);
}
});
DEMO HERE
You can do it this way with targeting specific item using parent() and next() selector and also i prefer to access specific field instead of index(such as eq) for input.
var schoolObj = $(this).parent().next().find(".school_Name");
schoolObj.val($(this).val());
if ($(this).val() == "other") {
schoolObj.prop('disabled', false);
schoolObj.val('');
} else {
schoolObj.prop('disabled', true);
}
Here is the Fiddle
You can have a look for jquery traversing:
parent: https://api.jquery.com/parent/
Next: https://api.jquery.com/next/
Find: https://api.jquery.com/find/
and for full traversing: https://api.jquery.com/category/traversing/

jQuery .on with .get methods

I am trying to get the tag name of the element clicked inside an li when the user clicks on the element. The li element is added dynamically to the HTML code. To do this I am using the code below however it does not seem to be working.
$('li *','div#contentWrapper').on('click','#interfaceContainer #left #sortableTestComponents li',function(e){
e.stopPropagation();
var domEl = $(this).get(0);
alert(domEl.tagName);
if(!$(event.target).hasClass("deleteTestComp")){
var type = $(this).find('div.headerName').html();
var information = $(this).find('input[type=hidden]').val();
if(type == "CliSessionType"){
parseCliComponent(information);
}
else if(type == "DBSessionType"){
parseDbComponent(information);
}
else{
parseScreenComponent(information);
}
}
});
Why is my code not working? Nothing happens when the user clicks on an element.
JSFiddle - http://jsfiddle.net/3FxQE/
Since you are interested in click events in li elements which comes under #interfaceContainer, the event registration must be $('#interfaceContainer').on('click','li',function(e){...});
Then to get the tagName, you need to use the actual source of the event this is available in e.target so you need to use $(e.target).get(0) to get the clicked dom element.
$('#interfaceContainer').on('click','li',function(e){
e.stopPropagation();
var domEl = $(e.target).get(0);
alert(domEl.tagName);
if(!$(event.target).hasClass("deleteTestComp")){
var type = $(this).find('div.headerName').html();
var information = $(this).find('input[type=hidden]').val();
if(type == "CliSessionType"){
parseCliComponent(information);
}
else if(type == "DBSessionType"){
parseDbComponent(information);
}
else{
parseScreenComponent(information);
}
}
});
Demo: Fiddle
You are trying to use a context where you don't need to, in your selector. Change $('li *','div#contentWrapper') with $('div#contentWrapper') and $(event.target) with $(e.target). A working fiddle is here
$('div#contentWrapper').on('click', '#interfaceContainer #left #sortableTestComponents li', function (e) {
e.stopPropagation();
var $this = $(this),
domEl = $this.get(0);
alert(domEl.tagName);
if (!$(e.target).hasClass("deleteTestComp")) {
var type = $this.find('div.headerName').html(),
information = $this.find('input[type=hidden]').val();
if (type == "CliSessionType") {
parseCliComponent(information);
} else if (type == "DBSessionType") {
parseDbComponent(information);
} else {
parseScreenComponent(information);
}
}
});

jQuery trigger event when click outside the element

$(document).click(function(evt) {
var target = evt.currentTarget;
var inside = $(".menuWraper");
if (target != inside) {
alert("bleep");
}
});
I am trying to figure out how to make it so that if a user clicks outside of a certain div (menuWraper), it triggers an event.. I realized I can just make every click fire an event, then check if the clicked currentTarget is same as the object selected from $(".menuWraper"). However, this doesn't work, currentTarget is HTML object(?) and $(".menuWraper") is Object object? I am very confused.
Just have your menuWraper element call event.stopPropagation() so that its click event doesn't bubble up to the document.
Try it out: http://jsfiddle.net/Py7Mu/
$(document).click(function() {
alert('clicked outside');
});
$(".menuWraper").click(function(event) {
alert('clicked inside');
event.stopPropagation();
});
http://api.jquery.com/event.stopPropagation/
Alternatively, you could return false; instead of using event.stopPropagation();
if you have child elements like dropdown menus
$('html').click(function(e) {
//if clicked element is not your element and parents aren't your div
if (e.target.id != 'your-div-id' && $(e.target).parents('#your-div-id').length == 0) {
//do stuff
}
});
The most common application here is closing on clicking the document but not when it came from within that element, for this you want to stop the bubbling, like this:
$(".menuWrapper").click(function(e) {
e.stopPropagation(); //stops click event from reaching document
});
$(document).click(function() {
$(".menuWrapper").hide(); //click came from somewhere else
});
All were doing here is preventing the click from bubbling up (via event.stopPrpagation()) when it came from within a .menuWrapper element. If this didn't happen, the click came from somewhere else, and will by default make it's way up to document, if it gets there, we hide those .menuWrapper elements.
try these..
$(document).click(function(evt) {
var target = evt.target.className;
var inside = $(".menuWraper");
//alert($(target).html());
if ($.trim(target) != '') {
if ($("." + target) != inside) {
alert("bleep");
}
}
});
$(document).click((e) => {
if ($.contains($(".the-one-you-can-click-and-should-still-open").get(0), e.target)) {
} else {
this.onClose();
}
});
I know that the question has been answered, but I hope my solution helps other people.
stopPropagation caused problems in my case, because I needed the click event for something else. Moreover, not every element should cause the div to be closed when clicked.
My solution:
$(document).click(function(e) {
if (($(e.target).closest("#mydiv").attr("id") != "mydiv") &&
$(e.target).closest("#div-exception").attr("id") != "div-exception") {
alert("Clicked outside!");
}
});
http://jsfiddle.net/NLDu3/
I do not think document fires the click event. Try using the body element to capture the click event. Might need to check on that...
This code will open the menu in question, and will setup a click listener event. When triggered it will loop through the target id's parents until it finds the menu id. If it doesn't, it will hide the menu because the user has clicked outside the menu. I've tested it and it works.
function tog_alerts(){
if($('#Element').css('display') == 'none'){
$('#Element').show();
setTimeout(function () {
document.body.addEventListener('click', Close_Alerts, false);
}, 500);
}
}
function Close_Alerts(e){
var current = e.target;
var check = 0;
while (current.parentNode){
current = current.parentNode
if(current.id == 'Element'){
check = 1;
}
}
if(check == 0){
document.body.removeEventListener('click', Close_Alerts, false);
$('#Element').hide();
}
}
function handler(event) {
var target = $(event.target);
if (!target.is("div.menuWraper")) {
alert("outside");
}
}
$("#myPage").click(handler);
try this one
$(document).click(function(event) {
if(event.target.id === 'xxx' )
return false;
else {
// do some this here
}
});
var visibleNotification = false;
function open_notification() {
if (visibleNotification == false) {
$('.notification-panel').css('visibility', 'visible');
visibleNotification = true;
} else {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
$(document).click(function (evt) {
var target = evt.target.className;
if(target!="fa fa-bell-o bell-notification")
{
var inside = $(".fa fa-bell-o bell-notification");
if ($.trim(target) != '') {
if ($("." + target) != inside) {
if (visibleNotification == true) {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
}
}
});

Categories

Resources