How do I convert this jquery code to JavaScript? - javascript

This is the jquery code below:
$('div').on('click', function() {
$(this).toggleClass('show-description');
});
I want to convert it to JavaScript because I get this error message:
"$ is undefined "
when I put the jquery code in the JavaScript section of codepen.io.
Is there a reason the jquery code is producing an error? How can I fix this?
If it is not possible to fix, how can I convert the Jquery code to JavaScript?
I'm trying to use toggleClass on all the divs when the div is clicked.
Here is a link to the codepen for reference: https://codepen.io/sophiesucode/pen/jOExXKw

Option 1: Use should push the jquery lib above </body>, Here is your demo
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Option 2: Use pure javascript like below
document.querySelector('div').onclick = function(){
this.classList.toggle("show-description");
};

$('div').on('click', function() {
$(this).toggleClass('show-description');
});
Can be represented by vanilla javascript as:
var divs = document.querySelectorAll('div'); //Get a list of all div elements
for (const div of divs){ //Loops through every div element
div.onclick = function(e) { //Adds the on click function to each
e.currentTarget.classList.toggle('show-description'); //Defines the function as toggling a class on the element of the click function
}
}
Jquery code actually is javascript. Jquery is a library built for javascript. To solve the error "$ is undefined" you would have to add jquery to your webpage, or import it in your script.
There is this wonderful article on W3 Schools which teaches multiple ways to add jquery to your webpages.

Your code doesn't work because you linked your script path as a relative path.
Change this
<script src="/assets/jquery.js"></script>
into this
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
another way is to link the jquery file using the settings menu in codepen.
Settings > Javascript > then search jquery in the CDNsearch bar

Related

Converting Jquery to javascript to avoid jquery library conflict

I have a jquery script that works the way I intend it to by appending a set of links within a div's class but unfortunately when I load the jquery library it kills my slider on my Wordpress site's page.
I am trying to rewrite the jquery to javascript so I don't have to rely on the library but am stumped on the syntax.
Here is the jquery that works:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var trail = '#announcements';
$(".pagination").find('a').attr('href', $(".pagination").find('a').attr('href') + trail);
});
</script>
And here is what I tried to write in javascript:
<script>
document.addEventListener("DOMContentLoaded", function(){
var trail = '#announcements';
var div = document.getElementsByClassName("pagination").find('a').attr('href',
this.find('a').attr('href') + trail);
});
</script>
Since this was more of an XY problem as pointed out I decided to look into why my jQuery wasn't working and discovered an error that was saying, $ is not a function similar to this post.
So with that in mind, I updated my jquery code and now it works without conflict.
Updated code:
<script>
jQuery(document).ready(function($){
$(document).ready(function() {
var trail = '#announcements';
$(".pagination").find('a').attr('href',
$(".pagination").find('a').attr('href') + trail);
});
});
</script>
I believe that a correct translation would look like this:
var trail = '#announcements';
var linksInPagination = Array.from(document.querySelectorAll('.pagination a'));
linksInPagination.forEach((link) => {
link.setAttribute('href', link.getAttribute('href') + trail );
});
Where are your mistakes?
var div = document.getElementsByClassName("pagination").find('a').attr('href',
this.find('a').attr('href') + trail);
document.getElementsByClassName("pagination") does not have .find() method.
Semanticaly it's defiently not a <div> but a Node Colection of <a> (so don't call it div :))
In jQuery you can use $('p').text('new text') for more than one <p> but in JS you have to loop and call it on elements directly. I'm converting a node collection to array and doing it with forEach method.

Jquery on Wordpress Frontend not woorking

Maybe I am so noob with jQuery but cant reach my objective. I need to add the attribute target="_blank to all the links inside certain divs. But anything I do works.
I have checked for jquery loaded with:
if(wp_script_is('jquery')==false) {
wp_enqueue_script("jquery");
}
Using the the following code nothing happens:
jQuery("#adagal").html("<p>asdf*</p>");
The #adagal element remains with previous content. I have checked in the source if my javascript file was correctly added, and it is.
<script type='text/javascript' src='http://localhost/wordpress/wp-content/plugins/AdManagerAdagal/js/ads/show_ad.js?ver=4.3.1'></script>
So, what is the problem¿?
Use that:
jQuery(document).ready(function($)
{
$(".your_class a").attr("target", "_blank");
});
Don't forget $ in ready(function to use jquery in your js

button in jquery and jscript

I am trying to understand the difference between JQuery and JavaScript.
And apologies if this is a silly question.
This is my attempt at JQuery. On pressing the button the text in <p> should change as requested. I cannot get this to work.
http://jsfiddle.net/QaHda/7/
this is my JavaScript attempt. I cannot get this to work either
http://jsfiddle.net/aLhb8/1/
Can someone please help me with
my jQuery above to get it working.
my jscript above to get it working.
I was trying to get to a point where I could write my JQuery in such a way that it could be written in javascript. Can anyone help me do this?
Thanks
EDIT
Thanks for all the answers/corrections: what I was looking for part 3 was this enter link description here which basically does part 1 using javaScript,I think. In future I should be careful,using left hand pane, to include Jquery library and to make sure jsript is wrapped in head/body
jQuery
You need to include jQuery library to your page by selecting a jQuery version in the first dropdown in the left panel
Demo: Fiddle
JS Sample
The problem is since your function is defined within the onload callback, it was not available in the global scope causing an error saying
Uncaught ReferenceError: myFunction is not defined
The solution is to add the script to the body elements, instead of inside the onload callback by selecting No Wrap - in <body> in the second dropdown in the left panel
function myFunction()
{
alert("Hello World!");
}
Demo: Fiddle
jQuery is library of javascript function and you need to add jquery file in html file that y jquery function was not working and for javacript function you need to change the setting in jfiddele left to no-wrap in head
http://jsfiddle.net/aLhb8/1/
http://jsfiddle.net/hushme/QaHda/10/
here is code
$("button").on("click", function () {
$("p").text("this text will now appear!!")
});
If you have internet connection, This should work
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
$(document).ready(function() {
$('button').click(function() {
alert("This is a simple alert message");
});
});
But if don't then just download the jquery framework and include into your page
Hope it helps and anyway jquery is a framework of javascript, so they are both or they are the same. Don't confuse yourself.
Here is a JavaScript version - http://jsfiddle.net/aLhb8/4/
JavaScript
var myButton = document.getElementById('myButton');
myButton.addEventListener('click', function(){
alert(myButton.textContent);
});
Check this link out if you want to start learning more about JavaScript - http://javascriptissexy.com/how-to-learn-javascript-properly/
For the pure JS code, on the top left panel, select 'No wrap - in body'. This will make your code run without a problem.
In the jQuery code, make sure you've selected the jQuery library, as opposed to pure JS. You hadn't selected this before, so your code was invalid.

Run JavaScript function on element defined with jQuery

Not sure I titled this well.. show's that I'm in unfamiliar territory. How can I run a JavaScript function based off of the element called in a jQuery function?
Theory:
<script type="text/javascript">
$.fillit('video');
</script>
(run fillit on video tag present in page.. interchangable with other elements)
$.fillit = function(){
this is where it says "run on the tag defined in the jQuery function"
}):
$.fn.extend({
fillit : function(){...}
});
then...
$('.video').fillit();
Edit (after comments)
To fill a dom element with other elements/html:
var img = document.createElement('img');
img.setAttribute('src', 'somesrc.jpg');
$('.video').append(img);
or
$('.video').html('<img src="somesrc.jpg"/>');
You can do it the way you described like so
<script type="text/javascript" language="javascript">
$.fillit = function(content)
{
$("result").html(content);
}
//call function
$.fillit("HELLO WORLD");
</script>
or as Alexander just posted if you want to do it on the selected element.
I don't think adding functions directly to jquery with $.func = is a good idea though. If jQuery ever adds a fillit method your method will conflict with theirs.
technopeasant, it sounds like you are using a jquery plugin (in your example, a plugin called 'fillit') and it is asking you to run the plugin on a tag or series of tags. Sorry if I misunderstood your question.
If that is the case, all you need to do is one of two things. If you are trying to run it on a very specific element in the HTML page (one with an id like <div id="myvideo"></div>) then all you need to do is run:
$('#myvideo').fillit();
//Notice the '#' symbol, that looks up the element with an id of 'myvideo'
If you want to run the plugin on a series of elements (like all <p> tags in the entire document, you'd run something like:
$('p').fillit()
//notice no '#', it's just looking up all <p> tags regardless of ID.
Take a look at the jQuery documentation regarding selectors to get a more concrete idea of how these selectors work:
http://docs.jquery.com/How_jQuery_Works
Someone answered with a link to this: http://docs.jquery.com/Plugins/Authoring
exactly what I was looking for. claim your kudos!
(function( $ ){
$.fn.fillit = function() {
this.fadeIn('normal', function(){
var container = $("<div />").attr("id", "filled")
.appendTo(container);
});
};
})( jQuery );

javascript to jquery

This function call ResizeableTextbox('myRT'); works well inside javascript(produces a resizeable text box) but doesn't work inside jQuery code.Why?
This produces the resizeable textbox.
<script type="text/javascript">
ResizeableTextbox('myRT');
</script>
But if I give it like this in the jquery code,I dont get the resizeable textbox.
$(".select").change(function () {
$(".select"+increment+" option:selected").each(function ()
{
if($(this).text() =='String')
{
$("<label id=labelid >"+label+"</label>").appendTo(".menu li");
ResizeableTextbox('myRT');//this does not work.How else to code?
}
});
});
Is there any method for function call in jQuery?
Update:
The function call ResizeableTextbox('myRT'); doesn't work anywhere within the jQuery code. It works only inside <script>.
How else to write this function call? some one help me please..
You want to append the resizable textbox to .menu li?
You could do this:
var rt = new ResizeableTextbox('myRT'); //this is for making resizeable text box
$('.menu li').append(rt);
However Im not quite sure if this is what you wan't. Your question is rather vague.
It depends greatly on exactly what 'rt' will contain and how it is then added to the DOM.
If it just contains HTML then obviously $(parentSelector).html(rt) would solve the problem.
If it returns a DOM element then $(rt).appendTo(parentSelector);
If it something else, or is added to the DOM inside your ResizeableTextbox code then I couldn't possibly guess.
Update: If you are using the resizable textbox detailed here: http://www.switchonthecode.com/tutorials/javascript-controls-resizeable-textbox then you would use the following code:
$(document).ready(function() {
var rt = new ResizeableTextbox();
$('#resizable').append(rt.GetContainer());
rt.StartListening();
});

Categories