I want Javascript code for respective jQuery function? - javascript

<script>
$(function () {
$('.headmenu li').click(function () {
$('.headmenu li').each(function (li) {
$(this).removeClass('selectedclass')
});
$(this).addClass('selectedclass');
});
});
</script>
Please give me alternative Javascript code for above jQuery Function.

You write multiple (nested) functions here:
Element.addEventlistener(event, callback) can be used to replace $.click().
Array.forEach(callback, this) can be used to replace $.each() (forEach is not (yet) available for every iterable type but you can "convert/cast" iterable types).
DOMTokenList.remove(token) can be used to replace $.removeClass() (element.classlist.remove('class').
DOMTokenList.add(token) can be used to replace $.addClass() (element.classlist.add('class').
NOTE: When using callbacks, you might need to use function.bind(this) to make sure the correct context is passed.
Please https://developer.mozilla.org/ for more information for these methods.

Related

Adding event listeners to multiple input elements using plain JS (not jQuery)

I have a code block that works perfectly in jQuery but it's the last bit of a project I am converting to plain vanilla Javascript with the specific aim to remove any and all dependencies on jQuery.
Here is the existing code block at issue:
$("input[data-pattern='comma']").on({
keyup: function() {inputComma($(this));}
});
How do I achieve this same functionality using ONLY plain pure JS?
Note: inputComma is a custom handler that conforms the value for EACH input element instance to a comma-delimited regex pattern as the user is typing.
If it helps, I tried...
document.querySelectorAll("input[data-pattern='comma']").forEach(function(elem) {
elem.addEventListener("keyup", function() {inputComma(elem);});
});
and also...
document.querySelectorAll("input[data-pattern='comma']").forEach(function(elem) {
elem.addEventListener("keyup", () => {inputComma(elem);});
});
I know jQuery's $(this) is different from "this" and that arrow functions also materially affect which "this" is being referenced. I tried to get around that issue by referencing the iterating object but I think that may be part of my problem. Not opposed to using the "this" pointer if there is a way to make it work in pure JS.
Thanks in advance for your help!
I think this can be better done using event delegation. It would look something like:
document.addEventListener(`keyup`, handle);
function handle(evt) {
if (evt.target.dataset?.pattern === `comma`) {
return inputComma(evt.target);
}
}
function inputComma(elem) {...}

Conver current jQuery code to valid vanilla Javascript

I have this jQuery code, but I need to convert it to vanilla Javascript because the project I am working on is not using jQuery
Here is what I have tried, but it is not working. I am unsure for all of these changes that I have made
// My current jQuery code
$('#category-2 ul li').each(function() {
$(this).find("ul.top-menu").parent().remove();
});
$('#category-2>a').html("Produkte");
// Vanilla JS
document.querySelectorAll('#category-2 ul li').forEach(function() {
this.find('ul.top-menu').parentNode().removeChild();
});
document.querySelectorAll('category-2>a').innerHTML="Produkte";
There are several problems in your code. One is that in the function you are using the this keyword as it would be in a class, but in functions the this keyword does not refer to what you would expect it to be. Instead use parameters from the forEach function: item, index, array, thisArg can be used.
The second problem is that in Vanilla JS there is no find() method so I would suggest implementing a ternary operator (one line if statement) to check if the className or the id includes what you are searching for.
I'm not sure what items are you searching for without the html it is hard to tell, but it would look something like this:
// Vanilla JS
document.querySelectorAll("#category-2").forEach(item => {
item.className.includes("top-menu") && item.parentNode.removeChild();
});
document.querySelectorAll("#category-2").forEach(item => {
item.innerHTML = "Produkte";
});

Creating a small jQuery plugin

I created this plugin to make work around an application easier.
Here is the link : http://jsfiddle.net/X5Squ/
My problem it that it always uses just 1 of the elements, please don't edit the data and data5 functions as these work perfectly for other parts but I need my function called jtoggle to work.
Any help much appreciated! Thanks.
$(document).ready(function (){$('.jtoggle').jtoggle(true);});
Have you tried using .each on this? I think the issue is that it isn't passing an array of DOM elements. I lack much experience in creating plugins, but it seems this can be easily averted by doing the following:
$(document).ready(function (){
$('.jtoggle').each(function(){
$(this).jtoggle(true);
});
});
(Which would also mean that you can safely remove the .each you have in jtoggle itself)
In your plugin you should act on each matched element and then return all the matched elements in order to maintain chainability:
$.fn.jtoggle = function (addUnderline) {
return this.each(function () {
// Do what you need on this matched element
});
};
Maintaining chainability means we can do stuff like:
$(".jtoggle").jtoggle(true).addClass("xyz");

How to translate such a function to jQuery?

So in my code I used
function $(id) {
return document.getElementById(id);
}
I want to move to jQuery. How to translate such thing to it?
Don't use this function, function $(id). Use the jQuery function $('#id'). This function will return an object with bunch of jQuery methods.
Methods include remove(), hide(), toggle(), etc., and the implementation is like $('#id').hide(), $('#id').show(), etc.
There are so many, many jQuery methods, that simplifies it in so many ways.
If I got your question right, you will need to include jQuery inside your page, and replace the following line:
return document.getElementById(id);
with this one:
return $("#"+id);
Using Jquery selectors you can do the same thing very easily.
$("#" + id)
For more details:
http://api.jquery.com/id-selector/
Just use
$("#"+id)
That will return the element with the right ID.

Using jQuery in a JavaScript function

function divlightbox(val)
{
if(val)
{
val=val.replace( /^\s+/g, "" );
var count_js=0;
var big_string='';
document.getElementById("video_lightbox").innerHTML="";
document.getElementById("divlightbox").style.display = "block";
$("#video_lightbox").css({"height":"430px","top":"10%","width":"480px"});
I found out that the error is in the above. My question is can't I use jQuery and traditional JavaScript at same time? I have done coding like this numerous times and never ran into a problem like this. I used to use jQuery methods like .hide() and .css() inside JavaScript functions but this time it doesn't work.
Thanks in advance.
While the other answers fix the specific problems, I don't think the OP's question (in bold) is really answered here, as depending on the specific context, $ may possibly not be defined as a jQuery object yet (having had this problem myself a few times now.)
In which case you would need to do something like:
function divlightbox(val) {
// ...
// just use jQuery instead of $ one time
jQuery("#video_lightbox").css({"height":"430px","top":"10%","width":"480px"});
}
OR
function divlightbox(val) {
// define the $ as jQuery for multiple uses
jQuery(function($) {
// ...
$("#video_lightbox").css("height":"430px");
$("#video_lightbox").css("top":"10%");
$("#video_lightbox").css("width":"480px");
});
}
jQuery is JavaScript so YES. Instead .innerHTML="" just use .empty(). Instead .getElementById() use $('#..') and so on.
to do things like hide(); and css() you need jquery objects. you can't do them to dom elements.
so you could do $('#video_lightbox').html("");
or
$('#video_lightbox').empty();
You must provide error in javascript console.
1) Do you pass a val argument to divlightbox function()? When do you call it?
2) why do you use the same identifier divlightbox both for a function and for a div id? Change name to the function please, maybe the problem could be here.
3) Always check if video_lightbox and divlightbox exist before accessing them.

Categories