How to translate such a function to jQuery? - javascript

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.

Related

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

Using javascript "this" for jquery selector

In this code, we can obtain value of element id as 2 differnt way and both way return resultat
$("#my_div").on("click", function () {
alert( $(this).attr("id") );
alert( this.id );
});
But i interest, second way, is it proper in this case? I ask this, because in code we use jquery selector and for jquery selector, write clear javascript: this is justified and will it work always? or may be better use jquery $(this) for jquery selector? or not differnce?
this.id will give you the internal DOM element property while $(this).attr("id") returns the value of 'id' attribute.
The alternative to this.id in jQuery is using prop() method: $(this).prop("id"). However, using pure this.id construction will be easier and faster.
The main jQuery constructor can take a number of different types of argument.
In that context, this is not a selector, it is an HTMLElementNode (which jQuery calls an element).
This is perfectly OK and documented.
There is no need to spend the resources in wrapping an element in a jQuery object if you are just going to grab its ID. There aren't any compatibility problems between browsers for that.
Grabbing the id property of an HTMLElementNode takes less code and is faster then wrapping the whole thing in jQuery.
Yes, your second way is proper.
$("#my_div").on("click", function () {
// this is available within this function
alert( this.id );
});
this refers to an HTMLDOMElement within the function, and wrapping that this within $() will give you an jQuery object.
If you define another function within the click handler. Ex:
$("#my_div").on("click", function () {
// keep reference of this
var that = this;
function test() {
// this will not available here directly
// instead of that you can use reference
alert(that.id);
}
});
And $(this).attr('id'), this.id or $(this).prop('id') will give you the same result.
For choosing the best method is not always clear.
In this case you want the this.id, because the other solution requires much more calls behind the scenes (obvious calls to jQuery and attr).
If you need more information that mite differ from browser, you want the jQuery way.

Convert Javascript function to jQuery plugin

I have already a short-hand function like so:
function myObj() {};
myObj.prototype.read = function (name) {alert(name);};
...(more functions)
Now I would like to "convert" this to a jQuery plugin.
What is the best way to do so? (My function doesn't need a selector before it).
I thought about doing it like this:
$.myObj.methodHere();
Thanks in advance.
Just add your method to the jQuery object.
$.myObj = myObj;
Then you can call it like:
$.myObj.methodHere();
EDIT: Why do you want to do this? jQuery plugins are supposed to act upon jQuery objects. Your function "doesn't need a selector before it", therefore it's not really a "plugin".

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");

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