jQuery code is making conflict with others - javascript

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

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.

velocity.js: $ is not defined

I am getting started with velocity.js and I included the file like this:
<script src="velocity.js"/> </script>
and in the script part I wrote
window.onload = function(){
$("div").velocity({opacity:1});
}
The rest of the function is only the css for the div, so not very important.
The problem I have is that I always get the error code:
Uncaught ReferenceError: $ is not defined
If I use jQuery with .animate no such problem appears (but in the code above I only use velocity).
If you don't want to use jQuery, you cannot use $.
I've never used it before, but if this tutorial is right, you could do:
window.onload = function(){
var divs = document.getElementsByTagName("div");
divs.forEach(function(el) {
Velocity(el, {opacity:1});
});
}
I think you have an conflict with jQuery. Try .noConflict() to avoid it.
See: https://api.jquery.com/jquery.noconflict/
$j.noConflict();
jQuery( document ).ready(function( $j ) {
// Code that uses jQuery's $j can follow here.
});
Have you tried this?
Velocity(document.getElementById("dummy"), { opacity: 0.5 }, { duration: 1000 });

jQuery works in jsFiddle, but not in Drupal

Good Evening,
I am pretty new to jQuery, and therefore would like you to forgive me if I am asking a stupid question, but apparently I've been facing the following problem, which I think I cannot solve by myself.
I am trying to implement jQuery code to change the order of columns a table has. The code is as follows:
$(document).ready(function (table, from, to) {
var rows = jQuery('tr', table);
var cols;
rows.each(function () {
cols = jQuery(this).children('th, td');
cols.eq(from).detach().insertBefore(cols.eq(to));
});
}(jQuery('#changeorder'), 1, 0));
It works perfectly Having a table with the id "changeorder" in jsFiddle, but doesn't work on Drupal website. I also tried removing the $(document).ready part, and adding (jQuery); at the end, the same result.
I tried adding the code to the html.tpl.php, just after the inclusion of jQuery javascript:
<!-- jQuery library (served from Google) -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function (table, from, to) {
var rows = jQuery('tr', table);
var cols;
rows.each(function () {
cols = jQuery(this).children('th, td');
cols.eq(from).detach().insertBefore(cols.eq(to));
});}(jQuery('#changeorder'), 1, 0));
</script>
And I have also tried adding the content directly to the page where I need it with the drupal_add_js(). Still no progress.
Any idea on what I'm doing wrong?
Thanks beforehand.
You should be wrapping your entire JS in (function ($) {})(jQuery);
Then using your $ in place of your jQuery instances...drupal has always liked this better for me.
I would also suggest converting this into a function that you can call when needed instead of passing your variable straight to the document ready like you currently are.
(function ($) {
$(document).ready(function() {
function tableChange(table, from, to){
var rows = $('tr', table);
var cols;
rows.each(function () {
cols = $(this).children('th, td');
cols.eq(from).detach().insertBefore(cols.eq(to));
};
tableChange('#changeorder', 1, 0)
});
})(jQuery);
In my experience best practice for drupal should not be adding your scripts to your html.tpl but instead you should be adding to yourtheme.info file:
scripts[] = yourjsfiles/script.js
Then in the script.js file you can have something like the following:
(function ($, Drupal, window, document, undefined) {
$(document).ready(function(){
//your code here
});
})(jQuery, Drupal, this, this.document);
You want to try and avoid cluttering up you .tpl files. You will thank me for this in the long run :)
edit: I just noticed in your question the inclusion of jquery. This cannot be done in the manner you are attempting to do it. By default Drupal 7 uses jquery 1.4.4 and the way to update this would be the jQuery Update Module

Uncaught ReferenceError: $ is not defined? Jsfiddle

I'm a beginner at javascript and i have used jsfiddle to create a navigation bar which appears when the user has scrolled down.
When i copy the code to dreamweaver it no longer works?
I have researched and it said something about adding the jquery framework or something?
Or is there a way to do this without the framework?
Link to jsfiddle for full code: http://jsfiddle.net/fNn7K/270/
javascript :
$(window).on('scroll', function () {
console.log($(this).scrollTop());
if ($(this).scrollTop() > 50) {
$('.nav').addClass('visible');
}else if ($(this).scrollTop() <= 50 && $('.nav').hasClass('visible')) {
$('.nav').removeClass('visible');
}
});
Without jQuery you can do :
window.onscroll = function() {
var display = document.body.scrollTop > 150 ? 'inline' : 'none',
elems = document.getElementsByTagName('nav');
for (var i=0; i<elems.length; i++) {
elems[i].style.display = display;
}
}
FIDDLE
When i copy the code to dreamweaver it no longer works?
JS Fiddle assembles a page based on several pieces of user entered data. One of those pieces of data is the selection of a library.
You have to copy the code to the right places in the document and include the same libraries.
Even then, the preview modes of Dreamweaver might not show it up, because they are (or at least were) entirely awful. Do you testing in a real browser.
I have researched and it said something about adding the jquery framework or something?
You need the jQuery library to use jQuery methods, yes.
Or is there a way to do this without the framework?
jQuery is just some JavaScript written by other people. You can reproduce anything it does. A line by line rewrite of your code to not use jQuery would be out of scope for a stackoverflow answer though.
you need to add jquery.js file in your code (dreamweaver)..
add this in between <head> tag
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
in the fiddle you provided, the jquery is already loaded..so you didn't get that error.
and don't forget to wrap your code inside document.ready function (which is again, already added in fiddle)..
$(function(){
$(window).on('scroll', function () {
.....
});
});

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.

Categories