javascript to jQuery or vice versa - javascript

I can just about struggle through with jquery, javascript less so.
I have a small function written in javascript, but I need to change the selectors. I wouldn't have any problem in doing this in jquery, but I do in js.
I need help either: converting my selector to its js equivalent, or converting the function in its entirety to jquery (as its only 4 lines of code).
function findNextTabStop() {
// This is the current selector
var universe = document.querySelectorAll("input");
// In jQuery, the NEW selector would look like this
$universe = $(this).closest(".form").find(".input-wrapper input, .input-wrapper select, .input-wrapper textarea");
var list = Array.prototype.filter.call(universe,
function (item) {
return item.tabIndex >= "0"
});
var index = list.indexOf(this);
return list[index + 1] || list[0];
}

After a bit of digging and testing, this is what I've come up with
function findNextTabStop() {
$el = $(this).closest(".input-step").find(inputs);
var index = $el.index(this);
return $el[index + 1] || $el[0];
}

Related

Each() issue in vanilla javascript

Everytime I try to reproduce .each() jQuery function in vanilla JavaScript, I'm in trouble.
When I try to change this :
$("[data-lng]").each(function(){
var lng = $(this).data('lng');
$('#language').text(lng)
});
To this :
var elem = document.querySelectorAll("[data-lng]");
Array.prototype.forEach.call(elem, function(){
document.getElementById('language').write = elem.dataset.lng
});
Console returns elem.dataset is not defined
Plus, I'm dealing with data stuff so I'm not even sure if its legal to write this document.querySelectorAll("[data-lng]")
Thanks for your help !
PS : Here is an example of what I want to convert into vanilla JS :
https://jsfiddle.net/x93oLad8/4/
Its fairly trivial to swap your jsFiddle example out for vanilla JS. One 'gotcha' to be aware of is that IE has no support for NodeList.prototype.forEach() hence using a regular for loop instead. (See: https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach)
var dictionary = {
'greet': {
'it': 'Ciao',
'en': 'Hello',
'fr': 'Salut',
}
};
var langs = ['it', 'en', 'fr'];
var current_lang_index = 0;
var current_lang = langs[current_lang_index];
window.change_lang = function() {
current_lang_index = ++current_lang_index % 3;
current_lang = langs[current_lang_index];
translate();
}
function translate() {
/* jQuery:
$("[data-translate]").each(function(){
var key = $(this).data('translate');
$(this).html(dictionary[key][current_lang] || "N/A");
});*/
/* vanilla */
var dt = document.querySelectorAll("[data-translate]");
//iterate over the NodeList:
for (i = 0; i < dt.length; ++i) {
var key = dt[i].getAttribute('data-translate');//get the key
dt[i].innerHTML = (dictionary[key][current_lang] || "N/A");//set the text
}
}
translate();
<div data-translate="greet"></div>
<button onclick="change_lang()">Change Language</button>
First of all, instead of using:
Array.prototype.forEach.call(elem, function()
You can just use
elem.forEach(function()
Secondly, callback function can accept arguments (3 of them to be specific):
el - current elem (which is the "this" you are looking for? :))
index - index of current elem in array
list - the nodelist you loop over
Usage:
elem.forEach(function(el, index, list){
console.log(el); //logs current element
});
Read more: https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach
#Edit: Since there was a big discussion in the comments about the first part, i feel obligated to link a thread on overriding default methods in JS: [].slice or Array.prototype.slice (a.k.a why elem.forEach might not work, just in case :))

How do I replace all instances of prices (beginning with "US$") in html page using jquery?

Say I have the following HTML:
<div class="L-shaped-icon-container">
<span class="L-shaped-icon">Something is US$50.25 and another thing is US$10.99.</span>
</div>
What I'd like to do is replace all instances of US$XX.xx with GBP£YY.yy on the live page using jquery.
The value of GBP would be determined by my own currency conversion ratio.
So I'm assuming what I'd first need to do is use a regular expression to get all instances of the prices which would be anything beginning with USD$ and ending after .xx? Prices will always have cents displayed.
Then I'm stuck what would be the best way to accomplish the next part.
Should I wrap these instances in a span tag with a class, then use jquery.each() function to loop through each and replace the contents with a jquery(this).html("GBP£YY.yy")?
Any help setting me on the right path would be greatly appreciated. Thanks guys.
base method for text replacements:
var textWalker = function (node, callback) {
var nodes = [node];
while (nodes.length > 0) {
node = nodes.shift();
for (var i = 0; i < node.childNodes.length; i++) {
var child = node.childNodes[i];
if (child.nodeType === child.TEXT_NODE)
callback(child);
else
nodes.push(child);
}
}
};
stuff you need to do:
var USDinGBP = 0.640573954;
textWalker(document, function (n) {
n.nodeValue = n.nodeValue.replace(/(USD?\$(\d+(\.\d+)?))/g, function($0, $1, $2){
return "GBP£" + (parseFloat($2) * USDinGBP).toFixed(2);
})
})
you can fire that on ANY site. it will even replace titles etc.
so.. to tell you about the benefits of not using jquery for this:
jquery will process and wrap every single element in a browser compatible way.
using a native javascript solution would speed up this process alot.
using native textnodes also is benefitial since it will not break event handlers for child elements.
you should also consider using fastdom.
it does not matter if you are using jquery or native js. after writing to elements the dom has to do certain tasks before it can be read again. in the end you will loose some time for each edited element.
to give you a fastdom example:
var textWalker = function (node, callback) {
var nodes = [node];
while (nodes.length > 0) {
node = nodes.shift();
for (var i = 0; i < node.childNodes.length; i++) {
var child = node.childNodes[i];
if (child.nodeType === child.TEXT_NODE)
callback(child);
else
nodes.push(child);
}
}
};
var textReplace = function (node, regex, callback) {
textWalker(node, function (n) {
fastdom.read(function () {
var text = n.nodeValue;
if (!regex.test(text)) {
return;
}
text = text.replace(regex, callback);
fastdom.write(function () {
n.nodeValue = text;
});
});
});
};
// put this function call into your onload function:
var USDinGBP = 0.640573954;
textReplace(document, /(USD?\$(\d+(\.\d+)?))/g, function($0, $1, $2){
return "GBP£" + (parseFloat($2) * USDinGBP).toFixed(2);
});
this will basically do the job in an instant.
if you want to go even further you could add this to jquery as following:
jQuery.fn.textReplace = function (regex, callback) {
this.each(function () {
textReplace(this, regex, callback);
});
};
and call it like that:
var USDinGBP = 0.640573954;
jQuery(".L-shaped-icon").textReplace(/(USD?\$(\d+(\.\d+)?))/g, function($0, $1, $2){
return "GBP£" + (parseFloat($2) * USDinGBP).toFixed(2);
});
If all of these values are directly in the span, if not you can give them a unique class and use it to iterate over them, you can use the following
You first get the numeric part of the string in a variable
convert the currency store it in other variable.
replace US$ with GBP
replace numeric part of the string with converted value
jQuery:
("span").each(function() {
var currencyVal=$(this).text().match(/\d/);
var convertedVal=currencyVal * 100; // just for example.
$(this).text($(this).text().replace(/^US$/,'GBP£'));
$(this).text($(this).text().replace(/\d/,convertedVal));
});
I hope this will helps you. Here is working Fiddle
HTML:
<div class="L-shaped-icon-container">
<span class="L-shaped-icon">Something is US$50.25 and another thing is US$10.99.</span>
<span class="L-shaped-icon">Something is BR$20.25 and another thing is US$10.99.</span>
<span class="L-shaped-icon">Something is US$10.25 and another thing is US$10.99.</span>
<span class="L-shaped-icon">Something is US$50.20 and another thing is GR$10.99.</span>
</div>
<button class="btnUpdate">Update</button>
JavaScript Code:
function UpdateCurrency(){
var UStoGB=10;
$('span').each(function(e){
var matchedText = $(this).text().match(/US\$\S+/g);
var updatedText = $(this).text();
if(matchedText){
for(var i=0;i<= matchedText.length;i++){
if(matchedText[i]){
var currentValue=matchedText[i].replace('US$','');
if(!currentValue) currentValue=0;
var newCurrency = ( parseFloat(currentValue) * UStoGB);
updatedText= updatedText.replace(matchedText[i],'GBP£'+newCurrency);
}
}
}
$(this).text(updatedText);
});
return false;
}

Detecting if input has been entered before

Lately I've been having trouble checking whether an input (player name) has been input more than once. This is not in-database, but just based on arrays contained within JavaScript. What I've been using after a couple of google searches was the indexOf() function. However this does not seem to work. My code is as follows:
var numberPlayers = 1;
var players = [];
var AddPlayer = function() {
if(!(players.indexOf($(".name")).val() > -1)) {
players.push($(".name").val());
$(".players").append("<p>Player number " + numberPlayers + " is " + $(".name").val() + "</p>");
numberPlayers++;
}
};
What method of detection would you recommend? I've tried looping, but wouldn't work either.
EDIT: Updated code. Still doesn't work!
Try this - note where the ) is placed:
if(!(players.indexOf($(".name").val()) > -1)) {
instead of:
if(!(players.indexOf($(".name")).val() > -1)) {
and actually, for readability this would be better:
var name = $('.name').val();
if ( players.indexOf(name) == -1)) {
In general, try adding console.log and breakpoints to find your bugs...
You can use an object (read Set / Hash) instead of an array; it should be faster anyway.
Note that I'm also using .text() which will escape text.
var numberPlayers = 1;
var players = {};
var AddPlayer = function() {
var newPlayer = $(".name").val();
if(!(newPlayer in players)) {
players[newPlayer] = true;
$(".players").append($("<p>").text("Player number " + numberPlayers + " is " + newPlayer));
numberPlayers++;
}
};
jQuery has a utility function for this:
$.inArray(value, array)
It returns the index of a value in an array. It returns -1 if the array does not contain the value.

Using JavaScript & jQuery in a single function (Nodes & Stuff)

I am currently learning jQuery. I know that jQuery is a custom library for JavaScript.
I am doing some learning examples in a book that is only using JavaScript, and to further my learning experience, I am trying to make use of jQuery for anything that might be more efficient.
So, I have this code:
function addLetter(foo) {
$(foo).unbind('click');
var tileLetter = $(foo).attr('class').split(' ');
var letter = tileLetter[2].charAt(1);
if (document.getElementById('currentWord').childNodes.length > 0) {
$('#currentWord p').append(letter);
} else {
var p = document.createElement('p');
var txt = document.createTextNode(letter);
p.appendChild(txt);
$('#currentWord').append(p);
}
}
Question #1:
If I change document.getElementById('currentWord').childNodes.length to $('#currentWord').childNodes.length it doesn't work. I thought the jQuery selector was the same thing as the JS document.getElementById as that it brought me back the DOM element. If that was the case, it'd make sense to be able to use the .childNodes.length functions on it; but it doesn't work. I guess it's not the same thing?
Question #2:
The code is textbook code. I have added all the jQuery that there is in it. My jQuery knowlede is limited, is there a more efficient way to execute the function?
The function's purpose:
This function is supposed to create a p element and fill it with a Text Node if it's the first time it's run. If the p element has already been created, it simply appends characters into it.
This is a word generating game, so you click on a letter and it gets added to a 'currentWord' div. The tile's letter is embedded in the 3rd css class, hence the attr splitting.
Thanks!
document.getElementById('currentWord')
returns a DOM object whereas $('#currentWord') returns a DOM object wrapped inside a jQuery object.
To get the plain DOM object you can do
$('#currentWord').get(0)
So
$('#currentWord').get(0).childNodes.length
should work.
Question #1:
jQuery returns a jQuery object. To return it to a regular javascript object use $(object)[0] and you can then treat it as a plain javascript (or DOM) object.
Question #2:
The efficiency looks good to me. Although you might want to use spans instead of p elements.
I guess one thing you could do (even though yours looks to run very fast) is cache the dom element:
function addLetter(foo) {
$(foo).unbind('click');
var tileLetter = $(foo).attr('class').split(' ');
var letter = tileLetter[2].charAt(1);
var currentWord = document.getElementById('currentWord');
if (currentWord.childNodes.length > 0) {
$(currentWord).find('p').append(letter);
} else {
var p = document.createElement('p');
p.innerHTML = letter;
currentWord.appendChild(p);
}
}
Calls to the jQuery() function ($()) return a jQuery object containing the matching elements, not the elements themselves.
Calling $('#some-id') will, then, return a jQuery object that contains the element that would be selected by doing document.getElementById('some-id'). In order to access that element directly, you can get it out of that jQuery object, using either the .get() function or an array index syntax: $('#some-id')[0] (it's 0-indexed).
I think you can replace all of this with a call to the text function.
function addLetter(foo) {
$(foo).unbind('click');
var tileLetter = $(foo).attr('class').split(' ');
var letter = tileLetter[2].charAt(1);
var currentWordP = $('#currentWord p');
if (currentWordP.size() > 0) {
currentWordP.text(currentWordP.text() + letter);
} else {
$('#currentWord').append("<p>" + letter + "</p>");
}
}
1: Use $.get(0) or $[0] to get the DOM element. e.x. $('#currentWord')[0].childNodes.length.
2: Try this:
function addLetter(foo) {
$(foo).unbind('click');
var tileLetter = $(foo).attr('class').split(' ');
var letter = tileLetter[2].charAt(1);
if ($('#currentWord p').length > 0) {
$('#currentWord p').append(letter);
} else {
$('#currentWord').append(
$('<p />', { text: letter })
);
}
}
Question #1:
document.getElementById returns DOM object. more
childNodes.length is property of Node object which is returned by document.getElementById.
jQuery selector returns jQuery object more. You can get DOM object from jQuery object using .get
$('#IDselector').get(0) = document.getElementById('IDselector')
Question #2:
function addLetter(foo) {
$(foo).unbind('click');
var tileLetter = $(foo).attr('class').split(' ');
var letter = tileLetter[2].charAt(1);
if ($('currentWord p').length > 0) {
$('#currentWord p').append(letter);
} else {
var p = $('<p />').text(letter);
$('#currentWord').append(p);
}
}

Show/Hide image before filtering a table isn't working

I have web page with some really large tables that I'm filtering using some jquery routines I wrote. Anyway, when these tables get really large and the filtering functions can take some time to complete. So I figured I'd unhide a animated gif so the user had some feedback. However, the gif never appears when I call:
$('#loadingimg').show();
Unless I put an alert statement in front of it. I apologize for the ugly code, I'm not an experienced jquery/javascript programmer.
function filter()
{
var eles = ["mtmprogram","rate","stage"];
var tag;
var classes='';
$('#loadingimg').show();
//alert('hi');
$('.report').hide();
for (var i in eles)
{
tag = '#' + eles[i] + ' option:selected';
if ($(tag).val())
{
//$('.'+ $(tag).val()).show();
classes = classes + '.' + $(tag).val();
}
}
if (classes == '')
$('tr.report').show();
else
$(classes).show();
filterSubtables('Loan Number');
$('#loadingimg').hide();
}
Many thanks!
Maybe you aren't giving the #loadingimg element enough time to display. You could test this by running the rest of your code in a timeout:
function filter()
{
var eles = ["mtmprogram","rate","stage"],
classes = '';
$('#loadingimg').show();
//alert('hi');
setTimeout(function () {
$('.report').hide();
for (var i = 0, len = eles.length; i < len; i++)
{
var $tag = $('#' + eles[i] + ' option:selected');
if ($tag.val())
{
//$('.'+ $tag.val()).show();
classes = classes + '.' + $tag.val();
}
}
if (classes == '')
$('.report').show();
else
$(classes).show();
filterSubtables('Loan Number');
$('#loadingimg').hide();
}, 500);
}
Notice that I changed how the tag variable is used (this creates less CPU overhead to make less jQuery selections and to use as local a variable as possible). I also changed your loop to a better format that performs amazingly faster than for ( a in b ): http://jsperf.com/jquery-each-vs-for-loops/2

Categories

Resources