Javascript Equivalent of Jquery - javascript

I am having problem in converting jquery to javascript as my application requirement is not to use jquery and only in plain html and javascript. I know how to write the code in Jquery but unable to convert it in javascript. My code is as follows
$(document).ready(function () {
$('input[type="button"').click(function () {
$(this).prop('disabled','disabled');
});
});
How to convert this code snippet to javascript.

Use window.onload to handle load-event on the window
document.querySelectorAll to select list of the elements within the document that match the specified group of selectors.
[].forEach.call to iterate through selected elements.
addEventListener to register the specified listener on the element.
window.onload = function() {
var elems = document.querySelectorAll('input[type="button"]');
[].forEach.call(elems, function(el) {
el.addEventListener('click', function() {
this.disabled = true;
});
});
};
Edit: document.addEventListener('DOMContentLoaded', function () {}); could be used instead of window.onload but consider Browser compatibility as well. Another easier alternate would be to place your <script> as last-child of <body> without wrapping your script in any load handler.

Use the DOMContentLoaded event as follow:
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
var btns = document.querySelectorAll("input[type=button]");
for (let i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
//Do stuff
console.log("button" + i + "clicked");
});
}
});

Related

Change Click Function to hover (Vanilla Javascript)

I am using this code:
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("div#logo1").onclick = function(){
hideAllImages();
document.getElementById("01").style.display="block";
removeNavHighlight();
document.getElementById("div#logo1").classList.add("my_active");
};
document.getElementById("div#logo2").onclick = function(){
hideAllImages();
document.getElementById("02").style.display="block";
removeNavHighlight();
document.getElementById("div#logo2").classList.add("my_active");
};
document.getElementById("div#logo3").onclick = function(){
hideAllImages();
document.getElementById("03").style.display="block";
removeNavHighlight();
document.getElementById("div#logo3").classList.add("my_active");
};
function hideAllImages() {
var items = document.getElementsByClassName('changing_text');
var itemsLen = items.length;
for(var i = 0; i < itemsLen; i++) {
items[i].style.display="none";
}
}});
Which working fine with click event but I want to convert it to be functional when I hover to the element.
What this function must to: for example, when I hover on an image other element must appear and previous element must become hidden.
This is Vanilla Javascript code.
Any suggestions? tried to change .onclick to .onmouseover but not working.
It's not .mouseover it's .onmouseover
Is it working for you to replace .onclick by .onmouseover?
These functions are always in format on<event>. It should be .onmouseover as the other answers have already said. Note that you'd be using mouseover if you were adding an event listener using the addEventListener function.

jQuery events: disable namespaces (or use an event with a period in the name)

I am trying to use .one() to bind to an event with the name similar to something.else.thing, I am not able to change the event name since it comes from an external library.
The problem is because of the periods, jQuery creates namespaces, else and thing for the event something instead of creating an event named something.else.thing.
Is there any way around this?
Thanks
Edit:
Some example code:
$(document).on('appfeel.cordova.admob.onAdLoaded', function() {
console.log('Does nothing');
});
document.addEventListener('appfeel.cordova.admob.onAdLoaded', function() {
console.log('Works');
});
I don't think you can disable jQuery event namespacing so if you want to use one on an event with dots in it you can just do this in pure JS:
Fiddle: http://jsfiddle.net/AtheistP3ace/8z6ewwnv/1/
HTML:
<div id="test"></div>
<button id="mybutton">Run event again</button>
JS:
var test = document.getElementById('test');
var button = document.getElementById('mybutton');
var event = new Event('something.else.blah');
function onWeirdEvent () {
test.removeEventListener('something.else.blah', onWeirdEvent);
alert('did it');
}
test.addEventListener('something.else.blah', onWeirdEvent, false);
test.dispatchEvent(event);
button.addEventListener('click', function (e) {
test.dispatchEvent(event);
}, false);
Its essentially the same thing. If you really want everything to seem jQuery-ish create a custom plugin:
Fiddle: http://jsfiddle.net/AtheistP3ace/8z6ewwnv/2/
$.fn.customOne = function (eventString, fn) {
var self = this[0];
var origFn = fn;
fn = function (event) {
self.removeEventListener(eventString, fn);
return origFn.apply(self);
};
self.addEventListener(eventString, fn, false);
};
$.fn.customTrigger = function (eventString) {
var event = new Event(eventString);
var self = this[0];
self.dispatchEvent(event);
}
$('#test').customOne('something.else.blah', function () {
alert('did it');
});
$('#test').customTrigger('something.else.blah');
$('#test').customTrigger('something.else.blah');
Here is how I decided to go about solving this issue. I went about it this way because this way allows me to continue to use jQuery and all the functionality it provides while keeping my code consistent and only requires a few lines of extra code to go about.
$(document).one('somethingElseThing', function() {
console.log('Event!');
});
document.addEventListener('something.else.thing', function() {
$(document).trigger('somethingElseThing');
});
What I am doing is using straight JavaScript to create an event listener for the event with a period in the name and then I have it trigger a custom event that doesn't a have a period so that I can continue to use jQuery. This I believe is an easy straightforward approach.

How to generate dynamically events in jquery?

I'm trying to set event attributes on a group of drop-down generated dynamically but for some reason the events aren't working.
Heres's my code.
$(document).ready(function () {
var idRoomTypesList = $("#idRoomTypesList").attr('value').split("_");
for (var i = 0; i < idRoomTypesList.length; i++) {
$("#roomTypeID-" + idRoomTypesList[i] + "_nRentedRooms").attr("onchange", generatePrice);
}
});
var generatePrice = function () {
alert(this.value().toString());
}
I think this must work for you
$(document).ready(function () {
var idRoomTypesList = $("#idRoomTypesList").attr('value').split("_");
for (var i = 0; i < idRoomTypesList.length; i++) {
$("#roomTypeID-" + idRoomTypesList[i] + "_nRentedRooms").on("change", generatePrice);
}
});
var generatePrice = function () {
alert($(this).val());
}
And have a look at this:
How to use the jQuery Selector in this web application?
HTML:
<select class="dynamicSelects">
....
</select>
JS:
var generatePrice = function () {
alert(this.value);
};
$(document).ready(function () {
$('body').on('change', '.dynamicSelects', generatePrice);
});
This is an example of using the on method provided by jQuery and delegating the events. This means that even if those drop downs are not in the DOM yet you can still attach the event to it and whenever they exist in the DOM the event will fire. It basically says attach these events to body but fire on elements with the class dynamicSelects. This covers adding any other dynamically generated drop downs with this class later as well.
Setting attributes to attach events, while it may work, should really be done using the on method or in plain JS the addEventListener, in my opinion.
Also when operating on plain DOM elements the value property is not a function so no value() is needed. Just this.value. And you don't need to convert it to a string because value returns a string. If it were a jquery object then you can do $(this).val() which is a function.
I only suggest this change of course because if you are going to use a library like jQuery at least take advantage of the things it offers.
Did you search into the jQuery documentation?
$(document).ready(function () {
var $idRoomTypesList = $("#idRoomTypesList").attr('value').split("_");
for (var i = 0; i < idRoomTypesList.length; i++) {
$("#roomTypeID-" + idRoomTypesList[i] + "_nRentedRooms").attr("onchange", generatePrice);
}
$( "#idRoomTypesList" ).change(generatePrice());
});
var generatePrice = function () {
alert(this.value().toString());
}

jQuery Replace DIV - Not working with 1.11

I am trying to load content from a hidden div container into an active container. This should be so simple. The code I have works fine with old jQuery, but is broken with the latest version. What am I missing here?
Here is my code in JSFiddle
http://jsfiddle.net/poaw07w4/
$('.campuslink').live('click', function () {
var id = $(this).attr("id").replace(/^.(\s+)?/, "");
var contentTobeLoaded = $("#faq_" + id).html();
$('#campusfaq').fadeOut(600,function(){
$('#campusfaq').html(contentTobeLoaded).fadeIn(500, function () {
});
});
e.preventDefault();
The live method was deprecated in version 1.7 and removed in version 1.9. You can use the on method to create a delegated event. (Don't forget the e parameter):
$(document).on('click', '.campuslink', function (e) {
Demo: http://jsfiddle.net/poaw07w4/3/
Note: Binding the event on the document element corresponds to how live worked. If possible you should use an element closer to the element where the event occurs, to reduce the overhead.
Try using .on('click') instead of .live('click')
https://jsfiddle.net/dotnetmensch/poaw07w4/1/
$('.campuslink').on('click', function () {
var id = $(this).attr("id").replace(/^.(\s+)?/, "");
var contentTobeLoaded = $("#faq_" + id).html();
$('#campusfaq').fadeOut(600, function () {
$('#campusfaq').html(contentTobeLoaded).fadeIn(500, function () {});
});
e.preventDefault();
});
The live() method has been deprecated since JQuery 1.7 (more here). If you replace it with the on() method, it should work fine (note also that preventDefault() is moved):
$('.campuslink').on('click', function (e) {
e.preventDefault();
var id = $(this).attr("id").replace(/^.(\s+)?/, "");
var contentTobeLoaded = $("#faq_" + id).html();
$('#campusfaq').fadeOut(600,function(){
$('#campusfaq').html(contentTobeLoaded).fadeIn(500, function () {
});
});

jQuery Bind each() and also click() on the same function

So I have the following fragment:
$(".server").each(function() {
var element = $(this);
//bunch of javascript here with element
});
I also want to bind a single click event for an id to do the same work as the above, how is this possible, without copying and pasting the entire block and doing:
$("#my-id").click(function() {
var element = $(this);
//bunch of javascript here with element
});
I think the following should work:
var eventHandler = function() {
var element = $(this);
//bunch of javascript here with element
};
$(".server").each(eventHandler);
$("#my-id").click(eventHandler);

Categories