Remove specific JS code with a click? - javascript

I've tried searching around but couldn't find a solution to this.
I am running two main JS functions on a site I am building. One which is lazy load, and one which is a smooth scroll, the latter for an anchor link to the bottom of the page.
However, with them both being present, they conflict each other as you can't anchor smooth scroll to the bottom of the page with lazyload... it just isn't happening.
Is there a way to disable lazyload if the user clicks on the anchor link? Thus making it work, and if they don't, then the lazyload works just fine?
Lazy Load:
<script>
$("img").lazyload({
threshold : 10000,
placeholder : "images/white.gif",
effect : "fadeIn"
});
</script>
Smooth scroll (although unfortunately this works for ALL anchor links... grrr):
<script>
$(document).ready(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}, 1400, function() {
location.hash = target;
});
});
}
}
});
// use the first element that is "scrollable"
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 [];
}
});
</script>
Thanks in advance,
R

You could replace the contents of the script with the contents surrounded by comments /* / on click and then re-enable by removing these comments / */. If the script never needs to be used again on the same page you could place the script inside a container element with an id and use jquery to remove that element from the page on click event. Another option that may work would be to alter the javascript to check a 'flag' that is toggled upon clicking the anchor link, the 'flag' can just be a javascript variable in the page that prevents the scripts you don't want to run from running.

Related

How to prevent Wordpress built-in “browse link” entering the data in wp-editor

Working with Wordpress Meta Box and I used the code of Dale Sattler from this How can I use the built in Wordpress “browse link” functionality? to create a custom field with wp browse link it works fine, but it inserted the data in wp-editor too.
I try to prevent the default event using code here Use WordPress link insert dialog in metabox? but doesn't work, I try that code too but it have a bug too.
here is my code
var _link_sideload = false; //used to track whether or not the link dialogue actually existed on this page, ie was wp_editor invoked.
var link_btn = (function($){
'use strict';
var _link_sideload = false; //used to track whether or not the link dialogue actually existed on this page, ie was wp_editor invoked.
var input_field = '';
/* PRIVATE METHODS
-------------------------------------------------------------- */
//add event listeners
function _init() {
$('body').on('click', '.link-btn', function(event) {
_addLinkListeners();
_link_sideload = false;
input_field = $(this).attr('href');
var link_val_container = $(input_field);
if ( typeof wpActiveEditor != 'undefined') {
wpLink.open();
wpLink.textarea = $(link_val_container);
} else {
window.wpActiveEditor = true;
_link_sideload = true;
wpLink.open();
wpLink.textarea = $(link_val_container);
}
return false;
});
}
/* LINK EDITOR EVENT HACKS
-------------------------------------------------------------- */
function _addLinkListeners() {
$('body').on('click', '#wp-link-submit', function(event) {
var linkAtts = wpLink.getAttrs();
console.log(linkAtts);
var link_val_container = $(input_field);
link_val_container.val(linkAtts.href);
_removeLinkListeners();
return false;
});
$('body').on('click', '#wp-link-cancel', function(event) {
_removeLinkListeners();
return false;
});
}
function _removeLinkListeners() {
if(_link_sideload){
if ( typeof wpActiveEditor != 'undefined') {
wpActiveEditor = undefined;
}
}
wpLink.close();
wpLink.textarea = $('html');//focus on document
$('body').off('click', '#wp-link-submit');
$('body').off('click', '#wp-link-cancel');
}
/* PUBLIC ACCESSOR METHODS
-------------------------------------------------------------- */
return {
init: _init,
};
})(jQuery);
please help, please ....
Ok I think I found a way to remove the link from the content. In your submit event you need to add:
$('body').on('click', '#wp-link-submit', function(event) {
var linkAtts = wpLink.getAttrs();
var link_val_container = $(input_field);
link_val_container.val(linkAtts.href);
var $frame = $('#content_ifr'),
$added_links = $frame.contents().find("a[data-mce-href]");
$added_links.each(function(){
if ($(this).attr('href') === linkAtts.href) {
$(this).remove();
}
});
_removeLinkListeners();
return false;
});
$('#content_ifr') is the iframe that loads tinymce editor with content inside. Since the iframe is loaded from the same domain you can mess around it (luckily). So you just go through its contents and you're looking for anchors that have data attribute called mce-href, and if the link that you've just added has the href value as the one you've added it removes them.
I re did this part of the code because I've noticed that all the links in my content had this attribute so you cannot just remove all anchors that have
data-mce-href attribute because that would remove all of them. And you only want to remove those you've added in your metabox.
This did the trick for me :)

How can I retain the scroll position of a scrollable area when pressing back button?

I have a long list of links inside a big scrollable div. Each time when a user click on a link then click the back button, it starts at the very top of the div. It is not user friendly to our users. Any ways to let the browser scroll to the previous position when pressing the back button?
Thank you very much!
During page unload, get the scroll position and store it in local storage. Then during page load, check local storage and set that scroll position. Assuming you have a div element with id element. In case it's for the page, please change the selector :)
$(function() {
$(window).unload(function() {
var scrollPosition = $("div#element").scrollTop();
localStorage.setItem("scrollPosition", scrollPosition);
});
if(localStorage.scrollPosition) {
$("div#element").scrollTop(localStorage.getItem("scrollPosition"));
}
});
I think we should save scroll data per page, also we should use session storage instead of local storage since session storge effects only the current tab while local storage shared between all tabs and windows of the same origin
$(function () {
var pathName = document.location.pathname;
window.onbeforeunload = function () {
var scrollPosition = $(document).scrollTop();
sessionStorage.setItem("scrollPosition_" + pathName, scrollPosition.toString());
}
if (sessionStorage["scrollPosition_" + pathName]) {
$(document).scrollTop(sessionStorage.getItem("scrollPosition_" + pathName));
}
});
I had the same problem with a simple user interface consisting of a fixed menu div and a scrolling document div ("pxeMainDiv" in the code example below). The following solution worked for me in Chrome 47.0.2526.106 m and in Firefox 43.0.3. (My application is for use in-house and I did not need to cater for old versions of IE).
$(document).ready(function(){
if (history.state) {
$("#pxeMainDiv").scrollTop(history.state.data);
}
$("#pxeMainDiv").scroll(function() {
var scrollPos = $("#pxeMainDiv").scrollTop();
var stateObj = { data: scrollPos };
history.replaceState(stateObj, "");
});
});
On the div scroll event, the scroll position of the div is stored in the state object inside the browser history object. Following a press of the Back button, on the document ready event, the scroll position of the div is restored to the value retrieved from the history.state object.
This solution should work for the reverse navigation of an arbitrarily long chain of links.
Documentation here: https://developer.mozilla.org/en-US/docs/Web/API/History_API
When using window.history.back(), this is actually default browser functionality as user SD. has pointed out.
On a site I am currently building, I wanted the logo of the company to backlink to the index page. Since jQuery 3, $(window).unload(function() should be rewritten to $(window).on('unload', function(). My code looks like this (using Kirby CMS' php syntax):
<?php if ($page->template() == 'home'): ?>
<script>
$(function() {
$(window).on("unload", function() {
var scrollPosition = $(window).scrollTop();
localStorage.setItem("scrollPosition", scrollPosition);
});
if(localStorage.scrollPosition) {
$(window).scrollTop(localStorage.getItem("scrollPosition"));
}
});
</script>
For anyone coming from react or anything similar to react router, here are two simple functions:
export function saveScrollPosition(context: any) {
let path = context.router.route.location.pathname;
let y = window.scrollY;
sessionStorage.setItem("scrollPosition_" + path, y.toString());
}
export function restoreScrollPosition(context: any) {
let path = context.router.route.location.pathname;
let y = Number(sessionStorage.getItem("scrollPosition_" + path));
window.scrollTo(0, y);
}
If a back button is kind of history back button window.history.back() Then what you are seeking for, is a default browser functionality. So you don't have to worry about it.
If your back button actually point to some URL in your application via link or form, then you have to take care that manually.
For solution you may use cookies to store your page scroll value. Each time user scroll on your page, do save scroll value for that page to cookie. Extra work is applied to manual cookie management.
window.onScroll = function(){
document.cookie="pageid=foo-"+window.scrollY+";";
}
This cookie value can be use to set scroll value of the page on page visit.
window.scroll(0,cookievalue);
With History api you can utilize scrollRestoration and stop browser from resetting scroll position.
Read it here. https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration
/* Use the below code to restore the scroll position of individual items and set focus to the last clicked item. */
(function ($)
{
if (sessionStorage)
$.fn.scrollKeeper = function (options)
{
var defauts =
{
key: 'default'
};
var params = $.extend(defauts, options);
var key = params.key;
var $this = $(this);
if (params.init === true)
{
var savedScroll = sessionStorage.getItem(key);
if (typeof savedScroll != 'undefined')
{
var int_savedScroll = parseInt(savedScroll);
if (int_savedScroll > 0)
$this.scrollTop(int_savedScroll);
setTimeout(function ()
{
var selectorFocus = sessionStorage.getItem(key + "-focus");
if (selectorFocus && selectorFocus != "")
$(document.querySelector(selectorFocus)).focus();
}, 100, key);
}
}
window.addEventListener("beforeunload", function ()
{
sessionStorage.setItem(key, $this.scrollTop());
if (document.activeElement)
{
var selectorFocus = elemToSelector(document.activeElement);
if (selectorFocus)
sessionStorage.setItem(key + "-focus", selectorFocus);
else
sessionStorage.setItem(key + "-focus", "");
}
else
sessionStorage.setItem(key + "-focus", "");
});
};
function elemToSelector(elem) /* written by Kévin Berthommier */
{
const {
tagName,
id,
className,
parentNode
} = elem;
if (tagName === 'HTML') return 'HTML';
let str = tagName;
str += (id !== '') ? `#${id}` : '';
if (className)
{
const classes = className.split(/\s/);
for (let i = 0; i < classes.length; i++)
{
if(typeof classes[i] === 'string' && classes[i].length > 0)
str += `.${classes[i]}`;
}
}
let childIndex = 1;
for (let e = elem; e.previousElementSibling; e = e.previousElementSibling)
{
childIndex += 1;
}
str += `:nth-child(${childIndex})`;
return `${elemToSelector(parentNode)} > ${str}`;
}
})(jQuery);
/*
Usage:
$('#tab1div').scrollKeeper({ key: 'uniq-key1', init: true });
If you don't need to restore the scroll positions (for example for restart), and you need just to save the scroll positions for the next time, use:
$('#tab1div').scrollKeeper({ key: 'uniq-key1', init: false });
*/

Two divs click event works only on one div

I'm using jquery and ajax to create a drawer (#DrawerContainer) and load content into it if I click a thumbnail in a gallery. My function is almost finished but I want to be able to close that drawer if I click again the opening button (now #current).
Here is a jsfiddle of my code: http://jsfiddle.net/RF6df/54/
The drawer element appears if you click a square/thumbnail, it's the blueish rectangle.
The current thumbnail is turned green.
I added a button in my drawer (not visible in the jsfiddle) to close it. I use this part of code for this purpose and it's working like a charm.
// Close the drawer
$(".CloseDrawer").click(function() {
$('#DrawerContainer').slideUp()
setTimeout(function(){ // then remove it...
$('#DrawerContainer').remove();
}, 300); // after 500ms.
return false;
});
Now I need my #current div to be able to close #DrawerContainer the same way .CloseDrawer does in the code above. Unfortunately adding a second trigger like this $("#current,.CloseDrawer").click(function() to my function isn't working... When clicking my "current" thumbnail, it just reopen the drawer instead of closing it...
How can I modify my code to close my #DrawerContainer with the "current" thumbnail?
Please keep in mind that I'm learning jquery, so if you can comment it could be of a great help. And please do not modify my markup or css, since everything works beside the closing part.
As per my understanding, you can use "toggle()" function which does exactly the same (i.e, toggle visiblity).
$('#DrawerContainer').toggle();
EDIT:
Updated the script to work.
$(document).ready(function() {
$.ajaxSetup({cache: false});
$('#portfolio-list>div:not(#DrawerContainer)').click(function() {
if ($(this).attr("id") != "current")
{
// modify hash for sharing purpose (remove the first part of the href)
var pathname = $(this).find('a')[0].href.split('/'),
l = pathname.length;
pathname = pathname[l-1] || pathname[l-2];
window.location.hash = "#!" + pathname;
$('#current').removeAttr('id');
$(this).attr('id', 'current');
// find first item in next row
var LastInRow = -1;
var top = $(this).offset().top;
if ($(this).next().length == 0 || $(this).next().offset().top != top) {
LastInRow = $(this);
}
else {
$(this).nextAll().each(function() {
if ($(this).offset().top != top) {
return false; // == break from .each()
}
LastInRow = $(this);
});
}
if (LastInRow === -1) {
LastInRow = $(this).parent().children().last();
}
// Ajout du drawer
var post_link = $(this).find('.mosaic-backdrop').attr("href");
$('#DrawerContainer').remove(); // remove existing, if any
$('<div/>').attr('id', 'DrawerContainer').css({display: 'none'}).data('citem', this).html("loading...").load(post_link + " #container > * ").insertAfter(LastInRow).slideDown(300);
return false; // stops the browser when content is loaded
}
else {
$('#DrawerContainer').slideUp(300);
$(this).removeAttr("id");
}
});
$(document).ajaxSuccess(function() {
Cufon('h1'); //refresh cufon
// Toggle/close the drawer
$("#current,.CloseDrawer").click(function() {
$('#DrawerContainer').slideToggle()
setTimeout(function(){ // then remove it...
$('#DrawerContainer').remove();
}, 300); // after 500ms.
return false;
});
});
//updated Ene's version
var hash = window.location.hash;
if ( hash.length > 0 ) {
hash = hash.replace('#!' , '' , hash );
$('a[href$="'+hash+'/"]').trigger('click');
}
});
Also, updated it here: Updated JS Fiddle
EDIT -2: Updated Link
Hope this Helps!!

Dynamic divs and scrollTop

I have a single page site:
http://chiaroscuro.telegraphbranding.com/
Each section is dynamically sized based on the user's window. I'm trying to figure out how to have a jQuery smooth scroll function scroll to the top of each section when the link is clicked. It is working great for the first section, funding areas, where I just used a simple offset().top, but the others are not working because they don't know how far to scroll because the window size is always different.
I've been trying to get offset() or position() to work, but no dice. I appreciate any advice.
Here's my jQuery:
`
$(document).ready(function () {
var slowScrollFunding = $('#funding-areas').offset().top;
var slowScrollAbout = $('#about-us').offset().top;
var slowScrollProjects = $('#our-projects').offset().top + 600;
panelOpen = true;
$('#anchor-funding-areas').click(function(event) {
event.preventDefault();
if(panelOpen == true) {
$('#slide-panel-content').stop(true, true).animate({height: '0px'}, 600, function() {
$('#panel-content-container').hide();
$('.scrollableArea').css('z-index', '11');
// Scroll down to 'slowScrollTop'
$('html, body, #home-wrap').animate({scrollTop:slowScrollFunding}, 1000);
panelOpen = false;
});
}else{
$('html, body, #home-wrap').animate({scrollTop:slowScrollFunding}, 1000);
};
});
$('#anchor-aboutus').click(function(event) {
event.preventDefault();
if(panelOpen == true) {
$('#slide-panel-content').stop(true, true).animate({height: '0px'}, 600, function() {
$('#panel-content-container').hide();
$('.scrollableArea').css('z-index', '11');
// Scroll down to 'slowScrollTop'
$('html, body, #aboutus-wrap').animate({scrollTop:slowScrollAbout}, 1000);
panelOpen = false;
});
}else{
$('html, body, #home-wrap').animate({scrollTop:slowScrollAbout}, 1000);
};
});
$('#anchor-ourprojects').click(function(event) {
event.preventDefault();
if(panelOpen == true) {
$('#slide-panel-content').stop(true, true).animate({height: '0px'}, 600, function() {
$('#panel-content-container').hide();
$('.scrollableArea').css('z-index', '11');
// Scroll down to 'slowScrollTop'
$('html, body, #home-wrap').animate({scrollTop:slowScrollProjects}, 1000);
panelOpen = false;
});
}else{
$('html, body, #home-wrap').animate({scrollTop:slowScrollProjects}, 1000);
};
});
$('#header-logo').add('.homelink').click(function() {
if(panelOpen == false) {
$('.scrollableArea').css('z-index', '0');
$('#panel-content-container').show();
$('#slide-panel-content').stop(true, true).animate({height: '389px'}, 600, function() {
// Scroll down to 'slowScrollTop'
panelOpen = true;
});
};
});
});
`
$.offset and $.position can be a little unreliable, especially if you have lots of complicated layouts going on - as your page does. What I've used in the past is the following trick:
var de = document.documentElement ? document.documentElement : document.body;
var elm = $('get_your_anchor_element').get(0);
var destScroll, curScroll = de.scrollTop;
/// check for the function scrollIntoView
if ( elm.scrollIntoView ) {
/// get the browser to scrollIntoView (this wont show up yet)
elm.scrollIntoView();
/// however the new scrollTop is calculated
destScroll = de.scrollTop;
/// then set the scrollTop back to where we were
de.scrollTop = curScroll;
/// you now have your correct scrollTop value
$(de).animate({scrollTop:destScroll});
}
else {
/// most browsers support scrollIntoView so I didn't bother
/// with a fallback, but you could just use window.location
/// and jump to the anchor.
}
The above can occur on the click event. The only thing that needs to be improved is that different browsers scroll on different base elements (body or html). When I used this I had my own element that was scrollable so I didn't need to work out which one the agent was using... When I get a second I'll see if I can find a good bit of code for detecting the difference.
The above has worked in all the modern browsers I've tested (Firefox, Safari, Chrome) however I didn't need to support Internet Explorer so I'm not sure with regard to that.
update:
I'm not quite sure what is going on with your implementation - it is possible that the page is so heavy with content that you actually can see the .scrollIntoView() happening - this has never been my experience, but then I didn't have so much going on on-screen. With that in mind, I've implemented a bare bones system that I would advise you use and build each extra part you need into it:
http://pebbl.co.uk/stackoverflow/13035183.html
That way you know you have a working system to start with, and will easily detect what it is that stops it from working. With regards to chiaro.js your implementation seems to be ok - if a little exploded over many different areas of the file - however this part is slightly erroneous:
$('#anchor-aboutus').click(function() {
event.preventDefault();
if(panelOpen == true) {
$('#slide-panel-content')
.stop(true, true)
.animate({height: '0px'}, 600, function() {
$('#panel-content-container').hide();
$('.scrollableArea').css('z-index', '11');
elm.scrollIntoView(true)
.animate({scrollTop:destScroll}, 1000);
panelOpen = false;
});
}else{
elm.scrollIntoView(true).animate({scrollTop:destScroll});
};
});
In the code above you will only get the correct value of destScroll if panelOpen === true. Ahh, actually I've also spotted another problem - which will explain why it's not working:
elm.scrollIntoView(true)
.animate({scrollTop:destScroll}, 1000);
The above code is mixing pure JavaScript and jQuery, the elm var is a normal DOM element (this supports the scrollIntoView method). But you are then attempting to chain the animate method of jQuery into the mix - you should also be triggering the animate method on the element responsible for the scrollbar. What you should use is as follows:
$('#anchor-aboutus').click(function(e) {
var currentScroll, destScroll;
e.preventDefault();
if(panelOpen == true) {
$('#slide-panel-content')
.stop(true, true)
.animate({height: '0px'}, 600, function() {
$('#panel-content-container').hide();
$('.scrollableArea').css('z-index', '11');
currentScroll = de.scrollTop;
elm.scrollIntoView(true);
destScroll = de.scrollTop;
de.scrollTop = currentScroll;
$(de).animate({scrollTop:destScroll}, 1000);
panelOpen = false;
});
}else{
currentScroll = de.scrollTop;
elm.scrollIntoView(true);
destScroll = de.scrollTop;
de.scrollTop = currentScroll;
$(de).animate({scrollTop:destScroll}, 1000);
};
});
However, what you will also need to do is make sure your de element points to the right element - either html or body depending on the browser - for this you can use this:
var de;
/// calculate which element is the scroller element
$('body, html').each(function(){
if ( this.scrollHeight > this.offsetHeight ) {
de = this;
return false;
}
});
alert( $(de).is('body') ) /// will be true for Chrome, false for Firefox.
You will need to use this code in place of the following code:
var de = document.documentElement ? document.documentElement : document.body;
The reason for changing the code you were using is as follows:
/// store the current scroll position from the de element
currentScroll = de.scrollTop;
/// get the browser to do the scrollTo calculation
elm.scrollIntoView(true);
/// store where the browser scrolled to behind the scenes
destScroll = de.scrollTop;
/// reset our scroll position to where we were before scrollIntoView()
/// if you don't reset then the animation will happen instantaneously
/// because that is what scrollIntoView does.
de.scrollTop = currentScroll;
/// wrap the normal dom element de with jquery and then animate
$(de).animate({scrollTop:destScroll}, 1000);

Javascript to rewrite all external links on mousedown?

How can i rewrite all external links with a single onmousedown event?
Kinda like what facebooks does with it's link shim
Please check the original Facebook Article about the link shim:
http://on.fb.me/zYAq0N
Requirements:
Should work for all subdomains on mainsite.com.
Should redirect example.com to
mainsite.com/link.cgi?u=http://example.com
Should only redirect links not belonging to mainsite.com.
Uses:
This is for security of the users of a private web app, and to protect referrers.
Best to do it on the fly for good UI as pointed out in the FB article.
That's so when users hovers over some link it shows the correct link but when he clicks it, js redirects it to my.site.com/link.cgi=http://link.com
Thanks in advance
SOLVED: https://gist.github.com/2342509
For an individual link:
function $(id){ return document.getElementById(id); }
$(link).onclick = function(){ this.href = "http://otherlink.com"; }
My Sheisty Link
So to get all external links:
window.onload = function(){
var links = document.getElementsByTagName("a");
for(a in links){
var thisLink = links[a].href.split("/")[2];
if(thisLink !=== window.location.hostname){
links[a].href = "http://mainsite.com/link.cgi?u=" + links[a]; }
// Or you could set onclick like the example above
// May need to accommodate "www"
}}
Edit:
Found this answer and got a better idea.
document.onclick = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
if (element.tagName == 'A') {
var link = element.href.split("/")[2];
if(link !=== window.location.hostname){
links[a].href = "http://mainsite.com/link.cgi?u=" + links[a]; }
return false; // prevent default action and stop event propagation
}else{ return true; }
}};
If you use jQuery then the following will work
$('a:link').mousedown(function() {
this.href = 'http://my.site.com/link.cgi=' + this.href;
});
Otherwise
var anchors = document.getElementsByTagName('a');
for(var i = 0; i < anchors.length; i++) {
var a = anchors[i];
if(a.href) {
a.addEventListener('mousedown', function(e) {
this.href = 'http://my.site.com/link.cgi=' + this.href;
}, false);
}
}

Categories

Resources