conflicting scripts not functioning - javascript

I have using 2 scripts declared on my footer. each script works perfectly when declared alone but if I declared the second one. the other function the other not.
Here is the code that works when declared alone and with the other script.
This has his own js file.
var fixed = false;
$(document).scroll(function() {
if( $(this).scrollTop() > 20 ) {
if( !fixed ) {
fixed = true;
$('.navbar-fixed-top').addClass('scroll');
}
} else {
if( fixed ) {
fixed = false;
$('.navbar-fixed-top').removeClass('scroll');
}
}
});
/*
* Smooth Scroll
*/
$(function() {
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}
var locationPath = filterPath(location.pathname);
var scrollElem = scrollableElement('html', 'body');
// Any links with hash tags in them (can't do ^= because of fully qualified URL potential)
$('a[href*=#]').each(function() {
// Ensure it's a same-page link
var thisPath = filterPath(this.pathname) || locationPath;
if ( locationPath == thisPath
&& (location.hostname == this.hostname || !this.hostname)
&& this.hash.replace(/#/,'') ) {
// Ensure target exists
var $target = $(this.hash), target = this.hash;
if (target) {
// Find location of target
var targetOffset = $target.offset().top;
$(this).click(function(event) {
// Prevent jump-down
event.preventDefault();
// Animate to target
$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
// Set hash in URL after animation successful
location.hash = target;
});
});
}
}
});
// Use the first element that is "scrollable" (cross-browser fix?)
function scrollableElement(els) {
for (var i = 0, argLength = arguments.length; i <argLength; i++) {
var el = arguments[i],
$scrollElement = $(el);
if ($scrollElement.scrollTop()> 0) {
return el;
} else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop()> 0;
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}
}
}
return [];
}
});
The other one is this declared below the first script. now this didn't work when the other is present but works perfectly when alone. also I tried the no conflicting script but same goes for the result.
<script>
$(document).ready(function(){
$(function(){
document.querySelector( "#nav-toggle" )
.addEventListener( "click", function() {
this.classList.toggle( "active" );
$(".navmobile").slideToggle();
});
});
$(window).resize(function() {
if ($(window).width() >= 767) {
$(".navmobile").hide();
}
else {
$("#nav-toggle").removeClass("active");
$(".navmobile").hide();
}
});
});
</script>

You probably have this element in your code:
Note the href="#" part - the first script is using event.preventDefault() for every A element with href that containing "#", so the second script doesn't get click event. remove the href="#" from that element (or leave the attribute empty) and it should work.

Change
// Any links with hash tags in them (can't do ^= because of fully qualified URL potential)
$('a[href*=#]').each(function() {
to
// Any links with hash tags in them (can't do ^= because of fully qualified URL potential)
$('a[href*=#]').not("#av-toggle").each(function() {
so the first script ignore the link you are clicking to do the toggling.

Related

How can I change style of element with jQuery function and media query when resize event working

I'm making a responsive web site, and I have some problems at resize.
I using media query at ww<1280, ww<1024, ww<640, then controll elements with Jquery Functions.
when document loaded, media query and functions are worked well.
but, when I try some jquery functions then resize window, there are so many problems.
one of function I wrote is,
var menuOpen = function() {
var ctryBtn = $(".countryMenu input[type=button]");
var ctryMenu = $(".countryMenu");
var subGnb = $("#subGnb");
var gnbBtn = $("#header button.mobileGnbBtn");
var myGnb = $("#gnb");
var schBtn = $(".mobileFindBtn");
var schMenu = $(".utilMenu");
var gnbDown = function () {
$("#gnb ul").append("<li class='mobileSiteMap'><a href='siteMap.html'>Site Map</a></li>");
myGnb.slideDown(500,function () {
$(".mobileGnbBtn").css({
"width":"37px",
"height":"37px",
"background-image":"url(image/common/btn-close-mobile.png)",
"background-size":"cover"
});
});
};
var gnbUp = function () {
if ($(window).width() <= 623) {
myGnb.slideUp(500, function () {
$(".mobileSiteMap").remove();
$(".mobileGnbBtn").css({
"width":"43px",
"height":"37px",
"background-image":"url(image/common/btn-menu-mobile.png)"
});
});
} else {
$(".mobileSiteMap").remove();
return false;
}
};
ctryBtn.on("click", function () {
if(isSubGNB === false){
subGnb.slideDown(500);
isSubGNB = true;
} else {
subGnb.slideUp(500);
isSubGNB = false;
}
});
gnbBtn.on("click", function () {
if(isGNB === false){
if(isSubGNB === true || isSearch === true){
subGnb.slideUp(500);
isSubGNB = false;
schMenu.slideUp(500);
isSearch = false;
ctryMenu.fadeIn(300);
}
gnbDown();
isGNB = true;
} else {
gnbUp();
isGNB = false;
}
});
schBtn.on("click", function () {
if (isSearch === false) {
if (isGNB === true || isSubGNB === true ) {
gnbUp();
isGNB = false;
subGnb.slideUp(500);
isSubGNB = false;
}
ctryMenu.fadeOut(100);
schMenu.slideDown(300);
isSearch = true;
} else {
schMenu.slideUp(100);
isSearch = false;
ctryMenu.fadeIn(300);
}
});
};
#gnb is absolute positioned at ww<640, invisible(display:none), and different children elements setting with another ww sizes.
#gnb is relative positioned at upper 640px ww.
Then I wrote resize event like:
$(window).on("resize", function () {
var gnbPC = function () {
$("#gnb").css({
"width":"410px",
"height":"76px",
"letter-spacing":"-0.04em",
"margin-left":"26.866%"
});
};
var toggleMobile = function () {
if ($(window).width() <= 623 ) {
$("#subGnb").css({"display":"none"});
} else {
gnbPC();
$("#subGnb").css({"display":"none"});
}
};
clearTimeout(timer);
timer = setTimeout(toggleMobile, delta);
});
I set var delta = null; var timer = null;
Under 640px ww, when I click button, #gnb slideDown, and slideUp well.
when #gnb slideUp, then I try resize to upper 640px,
there is no #gnb because it had invisibled when slideUp() finished.
So I try to give it CSS set(default value of CSS ww>640),
but it is written inline, then mediaQuery didn't work.
I want some solution, when I trying resize window,
function work then reload for default setting for ww size.
Or, solve this resizing problems.
I want reset when resize,
if #gnb opened, then I try resize, I want it closed then change to default setting for ww size.

Delay scrolling to anchor link

I am terrible with JS and possibly even worse at explaining what I'm doing so please bear with me. I have an external script that smooths the transitions on scrolling to anchor links. I want to delay the scroll on just one element.
External Script:
$(function() {
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}
var locationPath = filterPath(location.pathname);
var scrollElem = scrollableElement('html', 'body');
$('a[href*=#]').each(function() {
var thisPath = filterPath(this.pathname) || locationPath;
if ( locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/,'') ) {
var $target = $(this.hash), target = this.hash;
if (target) {
var targetOffset = $target.offset().top;
$(this).click(function(event) {
event.preventDefault();
$(scrollElem).animate({scrollTop: targetOffset}, 2600, function() {
location.hash = target;
});});}}});
function scrollableElement(els) {
for (var i = 0, argLength = arguments.length; i <argLength; i++) {
var el = arguments[i],
$scrollElement = $(el);
if ($scrollElement.scrollTop()> 0) {
return el;
} else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop()> 0;
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}}}return [];}});
It is embedded in the main php file like so:
<script src="smoothScroll.js"></script>
So this is totally wrong but what i want to do essentially:
<a href="#whatwedo" onClick="setTimeout(smoothScroll.js, 5000)">
What would be the best way of delaying the scroll for just this one element?
I guess you could match a specific anchor value from the href statically, even though it's sloppy.
https://jsfiddle.net/cpcnsd0v/
var delay;
$('a').click(function(e) {
e.preventDefault();
delay = 0;
if ($(this).attr('href').split('#')[1] === 'whatwedo') {
delay = 1000;
}
setTimeout(function() {
// do scroll here
},delay);
});

Conflict between two js scripts, I can't understand why?

I am trying to implement a tracking script that standalone and on other sites works just as intended (or atleast to what I can see from watching the sites and analytics).
The code looks like this
{
jQuery(document).ready(function($) {
var filetypes = /\.(zip|exe|dmg|pdf|doc.*|xls.*|ppt.*|mp3|txt|rar|wma|mov|avi|wmv|flv|wav)$/i;
var baseHref = '';
if (jQuery('base').attr('href') != undefined) baseHref = jQuery('base').attr('href');
jQuery('a').on('click', function(event) {
var el = jQuery(this);
var track = true;
var href = (typeof(el.attr('href')) != 'undefined' ) ? el.attr('href') :"";
var isThisDomain = href.match(document.domain.split('.').reverse()[1] + '.' + document.domain.split('.').reverse()[0]);
if (!href.match(/^javascript:/i)) {
var elEv = []; elEv.value=0, elEv.non_i=false;
if (href.match(/^mailto\:/i)) {
elEv.category = "Email";
elEv.action = "Klick";
elEv.label = href.replace(/^mailto\:/i, '');
elEv.loc = href;
}
else if (href.match(filetypes)) {
var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
elEv.category = "Nerladdning";
elEv.action = "Fil-" + extension[0];
elEv.label = href.replace(/ /g,"-");
elEv.loc = baseHref + href;
}
else if (href.match(/^https?\:/i) && !isThisDomain) {
elEv.category = "Ex.Länk";
elEv.action = "Klick";
elEv.label = href.replace(/^https?\:\/\//i, '');
elEv.non_i = true;
elEv.loc = href;
}
else track = false;
if (track) {
_gaq.push(['_trackEvent', elEv.category.toLowerCase(), elEv.action.toLowerCase(), elEv.label.toLowerCase(), elEv.value, elEv.non_i]);
if ( el.attr('target') == undefined || el.attr('target').toLowerCase() != '_blank') {
setTimeout(function() { location.href = elEv.loc; }, 400);
return false;
}
}
}
});
});
}
This is the jquery version that is loaded before
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js"></script>
Now onto the problem, if I place "my" script above the ones I will post below then my script works. But if I do it as I want, placing my script last on the page it does not work, or anywhere aslong as it is below the other one will end up with mine not working
<script type="text/javascript"> jQuery(document).ready(function ($) { runJS(); }); </script>
The runJS leads to another .js file that is functions.js, of what I can understand runJS is this (I replaced the name of the site with site below).
function runJS() {
if((fontLoaded('DistrictThin') && fontLoaded('NationalLight')) || timer > 30) {
site.init();
$(".search_result").find('img').load(function () {
$(".search_result.primary").equalHeights();
//$(".search_result:not(.primary)").equalHeights();
});
if ($('#site_search_form').length > 0) {
populateForm();
}
}
else {
setTimeout('runJS()', 100);
timer += 1;
}
}
Any help would be much appreciated!
if you using different version of jquery in single page you must use this
var jq = jQuery.noConflict (); // jq having the value of $.
// In your entire script use jq instead of $.

Unexpected order in script execution

Why is it running the second script and how can I make it work like a toggle control?
<script>
var el = 2;
$(document).ready(function(){
$(".rightDiv").click(function(){
if (el == 2) {
$(this).animate({left:'150px'});
el = 1;
}
});
});
</script>
<script>
$(document).ready(function(){
$(".rightDiv").click(function(){
if (el==1) {
$(this).animate({left:'50px'});
el = 2;
}
});
});
</script>
You only need one .ready()
$(document).ready(function()
{
var el = false;
var rightDivs = $('.rightDiv');
$(rightDivs).click(function(){
if (el == false)
{
$(this).animate({left:'150px'});
el = true;
}
else if (el == true)
{
$(this).animate({left:'50px'});
el = false;
}
});
});
This should work fine for you:
var el = false;
$(document).ready(function() {
$(".rightDiv").click(function() {
$(this).stop(true).animate({left: (el ? 50 : 150) + 'px'});
el = !el;
});
});​
jsfiddle with example
You have atteached two event handlers, so when the event happens it will run one, then the other.
As the first one will change the variable so that the condition in the second one becomes true, the code inside both if statements will run.
Put the code in the same event handler, so that you can use else to run only one of them:
<script>
$(document).ready(function(){
var el = 2;
$(".rightDiv").click(function(){
if (el == 2) {
$(this).animate({left:'150px'});
el = 1;
} else {
$(this).animate({left:'50px'});
el = 2;
}
});
});
</script>
here's a slightly improved version of #h2ooooooo 's answer, where we ditched the global scoped variable and use element's attributes.
Basically what we are doing here is to prevent bloating the global scope by using global variables and now we are working with data directly related to the element that was pressed.
$(document).ready(function() {
$(".rightDiv").attr("isLeft",1).click(function() {
var pos = "50";
if( $(this).attr("isLeft") == "1" ){
pos = "150";
$(this).attr("isLeft",0)
}else{
$(this).attr("isLeft",1);
}
$(this).stop(true).animate({left: pos + 'px'});
});
});

Get caret HTML position in contenteditable DIV

I am having troubles figuring out how to get caret position in a DIV container that contains HTML tags.
I am using this JavaScript function to do that:
function getCaretPosition()
{
if (window.getSelection && window.getSelection().getRangeAt)
{
var range = window.getSelection().getRangeAt(0);
var selectedObj = window.getSelection();
var rangeCount = 0;
var childNodes = selectedObj.anchorNode.parentNode.childNodes;
for (var i = 0; i < childNodes.length; i++)
{
if (childNodes[i] == selectedObj.anchorNode)
{
break;
}
if(childNodes[i].outerHTML)
{
rangeCount += childNodes[i].outerHTML.length;
}
else if(childNodes[i].nodeType == 3)
{
rangeCount += childNodes[i].textContent.length;
}
}
return range.startOffset + rangeCount;
}
return -1;
}
However, it finds a caret position of the text in my DIV container, when I need to find the caret position including HTML tags.
For example:
<DIV class="peCont" contenteditable="true">Text goes here along with <b>some <i>HTML</i> tags</b>.</DIV>;
(please note, that HTML tags are normal tags and are not displayed on the screen when the function is returning caret position)
If I click right between H and TML, the aforementioned function will find caret position without any problems. But I am getting the contents of DIV box in HTML format (including all tags), and if I want to insert something at that caret's position, I will be off by a few or many characters.
I went through many posts, but all I could find is either <TEXTAREA> caret postions, or functions similar to what I have posted. So far I still cannot find a solution to get a caret position in a text that has HTML formatting.
Can anyone help, please?
PS. Here's JQuery/Javascript code that I wrote for the link button:
$('#pageEditor').on('click', '.linkURL', function()
{
var cursorPosition;
cursorPosition = getCaretPosition();
var contentID = $(this).parent().parent().attr('id');
var userSelected = getSelectionHtml();
var checkLink = userSelected.search('</a>');
var anchorTag = 0;
if(checkLink == -1)
{
var currentContents = $('#'+contentID+' .peCont').html();
var indexOfSelection = currentContents.indexOf(userSelected);
var getPossibleAnchor = currentContents.slice(indexOfSelection, indexOfSelection+userSelected.length+6);
anchorTag = getPossibleAnchor.search('</a>');
}
if(checkLink > 0 || anchorTag > 0)
{
//alert(checkLink);
document.execCommand('unlink', false, false);
}
else
{
$('#'+contentID+' .peCont').append('<div id="linkEntry"><label for="urlLink">Please enter URL for the link:<label><input type="text" id="urlLink" /></div>');
$('#linkEntry').dialog({
buttons: {
"Ok": function()
{
var attribute = $('#urlLink').val();
var newContentWithLink = '';
if(attribute != '')
{
if(userSelected != '')
{
var currentContent = $('#'+contentID+' .peCont').html();
var replacement = ''+userSelected+'';
newContentWithLink = currentContent.replace(userSelected, replacement);
}
else
{
var currentTextContent = $('#'+contentID+' .peCont').html();
var userLink = ''+attribute+'';
if(cursorPosition > 0)
{
var contentBegin = currentTextContent.slice(0,cursorPosition);
var contentEnd = currentTextContent.slice(cursorPosition,currentTextContent.length);
newContentWithLink = contentBegin+userLink+contentEnd;
}
else
{
newContentWithLink = attribute+currentTextContent;
}
}
$('#'+contentID+' .peCont').empty();
$('#'+contentID+' .peCont').html(newContentWithLink);
}
$(this).dialog("close");
} },
closeOnEscape:true,
modal:true,
resizable:false,
show: { effect: 'drop', direction: "up" },
hide: { effect: 'drop', direction: "down" },
width:460,
closeText:'hide',
close: function()
{
$(this).remove();
}
});
$('#linkEntry').on('keypress', function(urlEnter)
{
if(urlEnter.which == 13)
{
var attribute = $('#urlLink').val();
var newContentWithLink = '';
if(userSelected != '')
{
var currentContent = $('#'+contentID+' .peCont').html();
var replacement = ''+userSelected+'';
newContentWithLink = currentContent.replace(userSelected, replacement);
}
else
{
var currentTextContent = $('#'+contentID+' .peCont').html();
var userLink = ''+attribute+'';
if(cursorPosition > 0)
{
var contentBegin = currentTextContent.slice(0,cursorPosition);
var contentEnd = currentTextContent.slice(cursorPosition,currentTextContent.length);
newContentWithLink = contentBegin+userLink+contentEnd;
}
else
{
newContentWithLink = attribute+currentTextContent;
}
}
$('#'+contentID+' .peCont').empty();
$('#'+contentID+' .peCont').html(newContentWithLink);
$(this).dialog("close");
}
});
}
});
I created a simple fiddle for you that does what you want.
This should work in recent versions of Firefox, Chrome and Safari.
It's your homework to add Opera and IE support if you need.

Categories

Resources