JavaScript: simple framework is not working properly - javascript

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

Related

Call a onkeyup function when click on other button jQuery

I have function which has keyup event on input field which is working fine.
I want to trigger this function also upon click on other button.
Here is my function
function validateChild(el) {
var validated = {};
console.log('Remove button clicked');
var dateOfBirthField = $(el).find('.date_of_birth');
$(dateOfBirthField).on("keyup", function () {
var dateOfBirthValue = $(el).find('.date_of_birth').val();
console.log('Check DoB');
if(validateDateOfBirth(dateOfBirthValue, dateOfBirthField)){
console.log('True');
validated.dateOfBirth = true;
} else {
validated.dateOfBirth = false;
}
validateButton(validated);
});
}
I'm calling this function on document load
function validateForms() {
$(document).find(".child-form").each(function () {
validateChild(this);
});
}
Here i have click event
.on('click', '.removeButton', function (event) {
validateForms();
});
When i click on this remove button it trigger but stop working after this
console.log('Remove button clicked');
How can i trigger keyup event also on this remove button, or there is better way to do this in javascript.
Can anyone help me with this?
Thanks
I have reviewed your three code blocks. Please try following three code blocks respectively.
Your function
function validateChild(dateOfBirthField) {
var validated = {};
var dateOfBirthValue = $(dateOfBirthField).val();
console.log('Check DoB');
if(validateDateOfBirth(dateOfBirthValue, dateOfBirthField)){
console.log('True');
validated.dateOfBirth = true;
} else {
validated.dateOfBirth = false;
}
validateButton(validated);
}
Call this function on document load
function validateForms() {
$('.child-form').on('keyup', '.date_of_birth', function() {
validateChild(this);
});
}
Click event
.on('click', '.removeButton', function() {
console.log('Remove button clicked');
$('.child-form .date_of_birth').each(function() {
validateChild(this);
});
});

How can I make this javascript function not use a global variable?

This function toggles the active state of a hamburger icon when clicking on it. Also clicking anywhere on the document does the same but only if the dropdown is open.
var dropdownOpen = false;
$(".hamburger").click(function () {
$(this).toggleClass('is-active');
dropdownOpen = !dropdownOpen;
});
$(document).ready(function(){
$(document).click(function(e){
if ($(e.target).is('.hamburger')) {
return;
}
else if (dropdownOpen === true)
{
$(".hamburger").toggleClass('is-active');
dropdownOpen = false;
}
});
});
How would I go about combining two click events so I don't have to use a global variable?
I've tried this:
$(document).ready(function(){
var dropdownOpen = false;
$(document).click(function(e){
if ($(e.target).is('.hamburger')) {
$('.hamburger').toggleClass('is-active');
dropdownOpen = !dropdownOpen;
}
else if (dropdownOpen === true)
{
$(".hamburger").toggleClass('is-active');
dropdownOpen = false;
}
});
});
..but it didn't work, any ideas?
You can wrap all your JS in an Immediately Invoked Function Expression. All the JS variables are not scoped to this function expression instead of being available globally.
(function() {
var dropdownOpen = false;
$(".hamburger").click(function() {
$(this).toggleClass('is-active');
dropdownOpen = !dropdownOpen;
});
$(document).ready(function() {
$(document).click(function(e) {
if ($(e.target).is('.hamburger')) {
return;
} else if (dropdownOpen === true) {
$(".hamburger").toggleClass('is-active');
dropdownOpen = false;
}
});
});
})();
There's no need for the global varable at all.
$(document).click(function(e) {
if ($(e.target).is(".hamburger")) {
$(e.target).toggleClass("is-active");
} else {
$(".hambuger").removeClass("is-active");
}
}
There's no harm in calling removeClass() if the class isn't there.

Creating a callback function containing if else statement

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....

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

jQuery: Check if button is clicked

I have two buttons in a form and want to check which one was clicked.
Everything works fine with radioButtons:
if($("input[#name='class']:checked").val() == 'A')
On simple submit button everything crash.
Thanks!
$('#submit1, #submit2').click(function () {
if (this.id == 'submit1') {
alert('Submit 1 clicked');
}
else if (this.id == 'submit2') {
alert('Submit 2 clicked');
}
});
You can use this:
$("#id").click(function()
{
$(this).data('clicked', true);
});
Now check it via an if statement:
if($("#id").data('clicked'))
{
// code here
}
For more information you can visit the jQuery website on the .data() function.
jQuery(':button').click(function () {
if (this.id == 'button1') {
alert('Button 1 was clicked');
}
else if (this.id == 'button2') {
alert('Button 2 was clicked');
}
});
EDIT:- This will work for all buttons.
$('input[type="button"]').click(function (e) {
if (e.target) {
alert(e.target.id + ' clicked');
}
});
you should tweak this a little (eg. use a name in stead of an id to alert), but this way you have more generic function.
$('#btn1, #btn2').click(function() {
let clickedButton = $(this).attr('id');
console.log(clickedButton);
});
try something like :
var focusout = false;
$("#Button1").click(function () {
if (focusout == true) {
focusout = false;
return;
}
else {
GetInfo();
}
});
$("#Text1").focusout(function () {
focusout = true;
GetInfo();
});

Categories

Resources