Converting Jquery to javascript to avoid jquery library conflict - javascript

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.

Related

How do I convert this jquery code to 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

Javascript code for Div slide down effect?

I've been trying to create a Div 'slide down' effect for quite a while now and I found this JS Fiddle which gives an example of exactly what I want; http://jsfiddle.net/L5P2Y/368/ . It uses this code:
$(document).ready(function() {
var $cont;
function tgl_conts(){
$('.content').stop().animate({height: 0},1200);
$cont.stop().animate({height:210},1200);
}
$('.tab').on('click',function(){
var tabClass=$(this).attr('class').split(' ')[1];
$cont = $('.'+tabClass+':not(.tab)');
var h = ($cont.height() === 0) ? tgl_conts() : ( $cont.stop().animate({height: 0},1200) );
});
});
I've copied all the code, including the HTML and CSS into my own document in the hope that I can just manipulate that into what I want. All I have is this exact code that is on the JS Fiddle, but I still cannot get the JavaScript to work despite it working fine in this example. I've pasted it between the head tags between two script tags but it still does not function. Why isn't it working? Is it in the wrong place? I'm very new to JavaScript.
Thanks
You need to load your code snippet after jQuery 1.7 is loaded on the page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
// you're code
</script>

jQuery code is making conflict with others

I am using a jquery code(given below) but when I am using this code then there are some forms in the site those are not working anymore I have tried by using jQuery.noConflict(); and $.noConflict(); but neither is working.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var topPart = $('#wrapper-29');
var origOffset = topPart.offset().top;
$(window).scroll(function () {
if ($(window).scrollTop() > origOffset) {
$('#wrapper-29').addClass('sticky');
$('#block-30').hide();
} else {
$('#wrapper-29').removeClass('sticky');
$('#block-30').show();
}
});
});
</script>
So can you please help me to solve this problem. Now I have removed the code as it is making problem. Thanks.
I don't know if this would apply to your case, but to avoid conflict between multiple versions of jQuery this is what I would do.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
(function($){
$(document).ready(function(){
var topPart = $('#wrapper-29');
var origOffset = topPart.offset().top;
$(window).scroll(function () {
if ($(window).scrollTop() > origOffset) {
$('#wrapper-29').addClass('sticky');
$('#block-30').hide();
} else {
$('#wrapper-29').removeClass('sticky');
$('#block-30').show();
}
});
});
}(jQuery.noConflict(true)));
// jQuery has been removed and is undefined at this point
// so no chance of conflicting with other version of jQuery
</script>
There are a couple issue - one is the use of jQuery.noConflict() and then referencing $ for jQuery. You can either replace the references of $ with jQuery, or as Felix Kling mentioned, reference the argument passed by jQuery.
Unless you need a specific reason for jQuery.noConflict(), I would recommend removing the call from your jQuery file.
This is what your updated code might look like:
<script>
jQuery(document).ready(function($){
var topPart = $('#wrapper-29');
var origOffset = topPart.offset().top;
$(window).scroll(function () {
if ($(window).scrollTop() > origOffset) {
$('#wrapper-29').addClass('sticky');
$('#block-30').hide();
} else {
$('#wrapper-29').removeClass('sticky');
$('#block-30').show();
}
});
});
</script>
Now, as you mentioned, when this script works, it breaks other pages with forms (ex: http://propertymanagementoh.com/pma/) - When I looked into it, I noticed a JS error being thrown by the sticky script.
My guess is you're using a CMS (looks like WordPress) that's generating IDs - so $('#wrapper-29') may exist on one page, but not on another page. If we revisit the code above and make the following changes:
<script>
jQuery(document).ready(function($){
var $topPart = $('.wrapper-first');
var $block = $('#block-30');
var origOffset = topPart.offset().top;
$(window).scroll(function () {
if ($(window).scrollTop() > origOffset) {
$topPart.addClass('sticky');
if ($block.length > 1) {
$block.hide();
}
} else {
$topPart.removeClass('sticky');
if ($block.length > 1) {
$block.show();
}
}
});
});
</script>
That should work on BOTH pages (I actually verified it works on both by using Charles Proxy and injecting that script). The main changes I made were:
1) Use the .wrapper-first class as a selector, since it's common between the pages.
2) Update the variable name to $topPart, a common naming convention to say "HEY! I'M A JQUERY OBJECT!"
3) Reference $('#block-30') as a $variable, but since it's NOT common between the two pages, we check the length property of the object, to see if we need to call show or hide -
This is NOT required (since jQuery will just silently fail...) I'd recommend using a unique class for this as well (especially if it will be on other pages).
Hopefully this helps!
If you want your header part fixed, there is a more simple and elegant way to do it:
$("header").css('position', 'fixed')
The position of the header will remain same regardless of browser's window position
If jQuery is not working simply edit the css file like below:
.header
{
position:fixed;
}
to change the header at scroll use scroll listener like below:
var b = $( "body" );
b.scroll(function(){
if ((b.scrollTop())>0){ // perform what you want to do
}
});

jquery and mootools conflict - one script works, another don't

Ok, I use mootools to display flash content through google maps and I work hard to make it work properly, so there is little chance to switch it to jQuery. On the other side, I see jQuery more useful to every other things so I'm trying to make it work together. That's for explanation. Now here is the code.
this jQuery script I use to show/hide animation and it works with mootools perfectly
<script type="text/javascript">
jQuery(document).ready(function() {
// hides the slickbox as soon as the DOM is ready
jQuery('#slickbox').hide();
// toggles the slickbox on clicking the noted link
jQuery('#slick-toggle').click(function() {
jQuery('#slickbox').toggle(400);
return false;
});
});
recently, I added scrit to animate flowing menu and I can't get it work. I've tried to apply noConflict, but it didn't work. Here is the code:
<script language="text/javascript">
var $j = jQuery.noConflict();
var name = "#floatMenu";
var menuYloc = null;
$j(document).ready(function(){
menuYloc = parseInt($j(name).css("top").substring(0,$j(name).css("top").indexOf("px")))
$j(window).scroll(function () {
offset = menuYloc+$(document).scrollTop()+"px";
$j(name).animate({top:offset},{duration:500,queue:false});
});
});
</script>
Error message is Uncaught TypeError: Object # has no method 'dispose'
Thank you very much.
Format your code this way, and there is no need to use noConflict(). Call jQuery.noConflict(); right after the jQuery and MooTools library have been loaded.
<script type="text/javascript">
(function($){
var name = "#floatMenu",
menuYloc = null;
$(document).ready(function(){
menuYloc = parseInt($(name).css("top").substring(0,$(name).css("top").indexOf("px")))
$(window).scroll(function () {
var offset = menuYloc+$(document).scrollTop()+"px";
$(name).animate({top:offset},{duration:500,queue:false});
});
});
})(jQuery);
</script>
This will encapsulate your code to a function, which will be passed the jQuery object. Anywhere you use $ inside that function it will reference jQuery.
Also, there is no attribute language with the value "text/javascript", it's the type attribute, which should have that value. Don't use the language attribute anymore.

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

Categories