the problem I have is that I would like to use an if else statement in a callback function like this:
alertNotify("alert","Do you want to delete this",function(delete) {
if(delete) {
//do code
}else {
//do nothing
}
});
current function code:
function alertNotify(text,type) {
$("body").append("<div id = 'alert' class='common'>\
<div id ='content'class='common'>\
</div>\
</div>");
var alert = $("<div id = 'ok' class='common'>\
Ok\
</div>\
<div id = 'cancle''class='common'>\
Cancle\
</div>");
var rename = $("<div class='common rename_it'>\
Ok\
</div>");
var type_file = $("<input type='text' id ='rename'><div id='hover'></div>");
if(type == "alert") {
$("#content").append(text);
$("#content").append(alert);
}
if(type == "rename") {
$("#content").append(rename);
$("#content").append(type_file);
}
$("#ok").click(function() {
$("div").remove("#alert");
});
$(".rename_it").click(function() {
$("div").remove("#alert");
});
$("#cancle").click(function() {
$("div").remove("#alert");
});
}
I would like the if statement to differentiate between whether the #ok div was clicked or the #cancel div was clicked but I have no idea where to start. Any ideas?
You can use confirm instead:
document.getElementById("prompt").onclick=function(){
if(confirm("Do you want to delete item?")){
// Delete
document.getElementById("status").innerHTML = "deleted";
}else{
// Don't delete
document.getElementById("status").innerHTML = "spared";
}
}
<button id="prompt">delete item</button>
<div id="status"></div>
It is possible that you are trying to do something like this
if( confirm("Do you want to delete this")){
//delete
}else{
// do not delete
}
In raw JavaScript your code might look something like:
//<![CDATA[
var pre = onload;
onload = function(){
if(pre)pre(); // if previous onload run here using this type of Event handler
var doc = document, bod = doc.body;
function E(id){
return doc.getElementById(id);
}
var ok = E('ok');
ok.onclick = function(){
console.log('ok was clicked');
}
// another way to use E
E('cancel').onclick = function(){
console.log('cancel was clicked');
}
}
//]]>
First you need event listeners on each element. So you can use something like
var element0 = document.getElementById(divID);
element0.addEventListener('click', funcDivClicked(element0));
To put a click event listener on all of them with a loop, see here:
Simple way to get element by id within a div tag?
I suggest using window.confirm instead of alert:
http://www.w3schools.com/js/js_popup.asp
function funcDivClicked(el){
var cBox = confirm("Delete "+el.getAttribute("id")+"?");
var strAction;
if (cBox == true) {
strAction = "You pressed OK";
//deletes the element
el.parentNode.removeChild(el);
} else {
strAction = "You pressed Cancel!";
}
console.log(strAction);
}
You could check the target within the event handler:
document.querySelector('body').addEventListener('click', function(e){
if(e.target.id === 'ok'){
alert('ok');
} else if(e.target.id === 'cancel'){
alert('cancel');
}
});
document.querySelector('body').addEventListener('click', function(e){
if(e.target.id === 'ok'){
alert('ok');
} else if(e.target.id === 'cancel'){
alert('cancel');
}
});
div {
color: white;
display: inline-block;
text-align: center;
height: 20px;
width: 100px;
}
div#ok {
background: green;
}
div#cancel {
background: red;
}
<div id="ok">Ok!</div>
<div id="cancel">Cancel!</div>
Sorry about that little bit of confusion. If I had of explained myself properly someone else might have answered but instead i got it. Add paremeter called callback and simply return callback(true); when the ok button is clicked and then my USB stopped working....
Related
so I tried making a simple on change fiddle. I can't get it to work. No matter what I do. WHY?
HTML CODE
<div id="status" style="display:none">0</div>
<button class="start">GO</button>
Javascript CODE
var cntTo = 2;
var cnt = 0;
$('#status').change( function() {
console.log('status changed');
if ($(this).text() == '1'){
if(cnt <= cntTo){
getNext(cnt);
}
}
});
$('.start').click(function(){
console.log('start clicked');
console.log('text of status now: ' + $('#status').text());
if($('#status').text() != '1'){
console.log('setting text');
$('#status').text('1');
console.log('text of status now: ' +$('#status').text());
}
});
function getNext(cnt){
$('#status').text('0');
console.log('getting details');
}
https://jsfiddle.net/hakz47vg/
The .change() function is limited to input, textarea, and select.
Source: https://api.jquery.com/change/
Use this
$('#status').bind("DOMSubtreeModified",function(){
var cntTo = 2;
var cnt = 0;
$(document).ready(function() {
$('.start').click(function() {
if ($('#status').text() != '1') {
$('#status').text('1');
}
});
$('#status').bind("DOMSubtreeModified",function(){
console.log('fired');
if ($(this).text() == '1') {
if (cnt <= cntTo) {
getNext(cnt);
}
}
});
});
function getNext(cnt) {
$('#status').text('0');
console.log('getting details');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="status" style="">0</div>
<button class="start">GO</button>
You can embed onchange function code directly with GO button click event like this:
$('.start').click(function(){
if($('#status').text() != '1'){
$('#status').text('1');
}
else
{
if(cnt <= cntTo){
getNext(cnt);
}
}
});
You are using change event which does not watch or respond to div content.Use DOMSubtreeModified event and trigger action on that event.
var cntTo = 2;
var cnt = 0;
$('#status').on("DOMSubtreeModified", function() {
if ($(this).text() == '1') {
if (cnt <= cntTo) {
getNext(cnt);
}
}
});
$('.start').click(function() {
if ($('#status').text() != '1') {
console.log('setting text');
$('#status').text('1');
console.log('text of status now: ' + $('#status').text());
}
});
function getNext(cnt) {
$('#status').text('0');
console.log('getting details');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="status" style="display:none">0</div>
<button class="start">GO</button>
If you want to do some action when the content modified inside the div element you have to use the event called DOMSubtreeModified like below.
$("body").on('DOMSubtreeModified', "#status", function() {
UPDATED FIDDLE
Reference:
For more information read out the thread already discussed about this in stack overflow.
jQuery Event : Detect changes to the html/text of a div
Use DOMSubtreeModified event
DOMSubtreeModified This is a general event for notification of all changes to the document. It can be used instead of the more specific mutation and mutation name events. Reference
$('#status').bind("DOMSubtreeModified",function(){
alert('changed');
});
Working fiddle
another simple solution
when text in #text changes in script fires a trigger and you can bind it to change event
var cntTo = 2;
var cnt = 0;
$('#status').bind('change', function () {
console.log('fired');
if ($(this).text() == '1'){
if(cnt <= cntTo){
getNext(cnt);
}
}
});
$('.start').click(function(){
if($('#status').text() != '1'){
$('#status').text('1');
$('#status').trigger('change');
}
});
function getNext(cnt){
$('#status').text('0');
console.log('getting details');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="status" style="display:none">0</div>
<button class="start">GO</button>
$("start").click function put inside in ready Function
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();
}
}
I am trying to create a JS framework.
Here is my JS code:
function $(id)
{
var info={
version:1.0
}
if(id)
{
if(window === this)
{
console.log('window id == '+id);
return new $(id);
}
console.log('id == '+id);
this.e = document.getElementById(id);
return this;
}
else{
return info;
}
}
$.prototype={
controller:function(pl)
{
if(typeof pl.events === 'function')
{
console.log('event is function');
}
},
click:function(callback)
{
this.e.addEventListener('click', callback, false);
return this;
}
};
Here I am calling this Framework
<div id='test'>
<div id='btn1'>Button1</div>
</div>
<div id='btn2'>Button2</div>
<script>
$('test').controller({
events:function()
{
$('btn1').click(function(){
alert('btn1 clicked');
});
}
});
$('btn2').click(function(){
alert('btn2 clicked');
});
</script>
OUTPUT
window id == test
id == test
event is function
window id == btn2
id == btn2
The problem is btn1 click event is not working but btn2 click is working. Can somone suggest some solution or some better way to make a JS frame work?
The problem is btn1 click event is not working
Well, you were not attaching a listener to it. You did pass a function to the controller method which could have done this, but it was never called.
controller: function(pl) {
if (typeof pl.events === 'function') {
console.log('event is function'); // but do nothing?
// add this:
pl.events();
}
}
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);
}
}
});
$(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;
}
}
}
}
});