How do you implement deep linking on a page so when the user comes that that page from an external link, that fancybox modal is initiated. I'm new to JS/Jquery
I was looking for the same thing this morning and found your question as well as a forum post that has an answer.
(function()
{
var qs = location.search.slice( 1 ),
params = qs.match( /&?ab=(\d+)\|(\d+)/ );
if( params )
page( Number( params[ 1 ] ), Number( params[ 2 ] ) );
})();
"Then if you link to that page passing your two numeric parameters in this form:
concert.html?ab=1|5
It should have the stunning effect of calling page(1, 5); when the page loads. "
http://www.webdeveloper.com/forum/showthread.php?t=247899
Hope it helps - it helped me. :)
I just solved it for myself with fancybox2 and url hashes.
You can use Fancybox callbacks to set and unset hashes.
I used data attributes in the img tag to store img identifiers.
Then you can check for a hash in the url at pageload, get the index and open the fancybox with the given index.
var option = {
afterLoad: function(links) {
var title = links.element.attr('data-my-img');
location.hash = title;
},
afterClose: function() {
location.hash = '';
}
},
hash = location.hash.substr(1),
gallery = $('.fancybox');
if(hash.length > 0){
//id
var i = null;
gallery.each(function(index) {
var o = $(this).attr('data-my-img');
if($(this).attr('data-my-img') == hash){
i = index;
return;
}
});
if(i != null){
option.index = i;
$.fancybox.open(gallery, option);
}
}
gallery.fancybox(option);
Related
I've got a dropdown box with a bunch of options for an image. Each image has an id in the database. The images are located in foo/images/ and are named after their id's in the database (21.gif, 32.png etc). The problem I'm having is testing to see if which extension works and use that one. Here's my code so far, i recently added the $.get(lnk) portion as a bad attempt, I'm new to Jquery. My thought process is if it was the right extension it would return true and be fine, and if it failed have it repeat until it returned true. Any way to do this? explain like im five
<SELECT NAME=IMG1 onchange=\'
this.form.SIGN_NFPA.selectedIndex = 0;
var id = this.options[this.selectedIndex].value
var exts = ["png", "gif", "jpg", "jpeg"];
var count = 0;
var lnk = (id) ? "foo/images/"+id+"."+exts[count] : "blank.gif";
window.document.IMG1.src = lnk;
$.get(lnk)
.done(function() {
return true;
}).fail(function() {
count = count + 1;
lnk = (id) ? "foo/images/"+id+"."+exts[count] : "blank.gif";
})
return true;
\'>
I've commented the code to help make it more readable.
$( "#select" ).on( "change", function () {
// grab the value for the select box
var val = $( this ).val();
// file extensions
var exts = [ "gif", "png", "jpg", "jpeg" ];
// set img = false, used to detect if img exists.
var img = false;
// set i = 0, stops the while looping forever
var i = 0;
var url;
// while image is false and there are more extensions to try
while ( !img && i < exts.length ) {
// set the url
url = "foo/images/" + val + "." + exts[ i ];
// build and send a request to see i the image exists.
var req = new XMLHttpRequest();
req.open( 'GET', url, false );
req.send();
// set img to the request status
img = req.status == 200;
// add 1 to i
i++;
}
// if no url, set url to "blank.gif"
url = img ? url : "blank.gif";
// set the image src attribute.
$( "#" + val ).attr( "src", url );
} );
I hope this helps.
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 });
*/
I'm sending a specific value through url and after that my page get refreshes.
The URL value is dynamic.Whenever URL sets I want to show div which is already hidden.
<button id="show_id" onclick="location.href='opdcasepaperreport.php?patient_nm='+document.getElementById('patient_id').value;" > View Report </button>
When user clicks on View Report , report div will be displayed.
I tried following 2 coding methods:
$( document ).ready(function()
{
$("#show_id").click(function()
{
$('#main').toggle();
});
});
and
$(document).ready(function ()
{
if(window.location.href.indexOf("?patient_nm"))
{
//alert("your url contains ");
//show code;
}
});
in 1st case because of page refresh div get visible and un visible again.
Is there any solution for this like in php if(isset(---)){//do this;}
Changing location.href value will refresh the page anyway.
In order to hide/show div depending on url value you need to:
get the value by searching in url params.
show / hide div.
Get URL params.
You can use this script in order to get url params:
var getQuery = function () {
var url_params = {};
var query = window.location.search.substring(1);
if (query.length === 0) return false;
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (typeof url_params[pair[0]] === "undefined") {
url_params[pair[0]] = pair[1];
} else if (typeof url_params[pair[0]] === "string") {
var arr = [ url_params[pair[0]], pair[1] ];
url_params[pair[0]] = arr;
} else {
url_params[pair[0]].push(pair[1]);
}
}
return url_params;
};
It will return an object (key, value).
Show / Hide div
If you using jQuery, you can simply is .toggle()
$("#your_div_name").toggle();
Or by using .show() / .hide()
So:
var query = getQuery();
if (query && query.some_param !== undefined) {
$("#your_div_name").show()
} else {
$("#your_div_name").hide()
}
But it's better not to use url params in order to change view.
Have fun.
How about this:
$("#show_id").click(function(e)
{
e.preventDefault();//this will prevent page refresh
$('#main').toggle();
});
Try following code:
$( document ).ready(function()
{
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var hasParam = getParameterByName('patient_nm');
if(hasParam !== 'undefined') {
$('#main').toggle();
}
});
As per your code, on button click the element will get toggled but after that the page gets refreshed immediately. On page refresh the element will be hidden again, so you are not able to view the effect.
As per my code above, when the page refreshes/loads, it will search for the parameter "patient_nm" that you are adding in the URL. If this parameter is not empty it will toggle the element. Since this process happens after page load, you will be able to see the results.
Hope this helps.
In my CKEditor I removed the 'linkType' and 'protocol' inputs of the link dialog.
CKEDITOR.on( 'dialogDefinition', function( ev )
{
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
if ( dialogName == 'link' )
{
var infoTab = dialogDefinition.getContents( 'info' );
infoTab.remove( 'linkType' );
infoTab.remove( 'protocol' );
}
});
However, evertype I type in something like https://google.com as soon as I type in the 'g' the https:// gets removed.
I checked the output and it always says http:// disregarding the input.
How can I turn this stupid behaviour off?
After much research, debugging and tweaking, I've finally managed to pull this off!!!
Here's how I do it:
CKEDITOR.on('dialogDefinition', function(e) {
// NOTE: this is an instance of CKEDITOR.dialog.definitionObject
var dd = e.data.definition;
if (e.data.name === 'link') {
dd.minHeight = 30;
// remove the unwanted tabs
dd.removeContents('advanced');
dd.removeContents('target');
dd.removeContents('upload');
// remove all elements from the 'info' tab
var tabInfo = dd.getContents('info');
while (tabInfo.elements.length > 0) {
tabInfo.remove(tabInfo.elements[0].id);
}
// add a simple URL text field
tabInfo.add({
type : 'text',
id : 'urlNew',
label : 'URL',
setup : function(data) {
var value = '';
if (data.url) {
if (data.url.protocol) {
value += data.url.protocol;
}
if (data.url.url) {
value += data.url.url;
}
} else if (data.email && data.email.address) {
value = 'mailto:' + data.email.address;
}
this.setValue(value);
},
commit : function(data) {
data.url = { protocol: '', url: this.getValue() };
}
});
}
});
Here's how I removed the protocol in v4.5.1:
CKEDITOR.on('dialogDefinition', function(ev) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
if (dialogName === 'link') {
var infoTab = dialogDefinition.getContents('info');
infoTab.remove('protocol');
var url = infoTab.get('url');
url.onKeyUp = function(){};
url.setup = function(data) {
this.allowOnChange = false;
if (data.url) {
var value = '';
if (data.url.protocol) {
value += data.url.protocol;
}
if (data.url.url) {
value += data.url.url;
}
this.setValue(value);
}
this.allowOnChange = true;
};
url.commit = function(data) {
data.url = { protocol: '', url: this.getValue() };
};
}
});
I'm afraid there's no way to change it. You have to manually edit a few lines of the code to make it working your way.
I recently found a way to hide the Link Type so you don't have to remove it totally. Set the style to display: none like the following:
infoTab.get( 'linkType' ).style = 'display: none';
I think it works for the Protocol as well, but I haven't tested it. I answered the same question here
Hope this helps someone!
For the lazy people like me, just do a quick core file hack:
open plugins/link/dialogs/link.js
in the minimized version find d=/^(http|https|ftp|news):\/\/(?=.)/i.exec(b);
remove http|https|ftp|
save file, upload it to your server
If it does not work after reload, this might be a cache problem. Open browser in private mode, navigate to your ckeditor and try it again. Good luck.
I'm trying to remove a landing page when I click on a link on a page. The page isn't mine so I'm trying to change the href with a user script.
Without any modification, the link looks like this:
https://www.domain.com/out.php?u=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPUZ1bC-1XjA%26amp%3Bfeature%3Drelated
What I want:
http://www.youtube.com/watch?v=PUZ1bC-1XjA&feature=related
What I got so far:
http://www.youtube.com%2fwatch%3fv%3dpuz1bc-1xja%26amp%3bfeature%3drelated/
But that adress doesn't work in the browser.
This is my current code:
$('a').each(function(index) {
var aLink = $(this).attr('href');
if(aLink) {
if(aLink.indexOf("out.php?u=") > 0) {
aLink = aLink.substring(51);
console.log(aLink);
$(this).attr('href', "http://"+aLink);
console.log($(this).prop('href'));
}
}
});
All help and tips are appreciated.
You need to decode the URL using decodeURIComponent
Change:
$(this).attr('href', "http://"+aLink);
To:
$(this).attr('href', 'http://' + decodeURIComponent(aLink));
Take a look at decodeURIComponent
You can also make use of the hostname, pathname, and search parameters of anchor elements.
// general function to turn query strings into objects
function deserialize_query_string(qs) {
var params = {};
var fields = qs.split('&');
var field;
for (var i=0; i<fields.length; i++) {
field = fields[i].split('=');
field[0] = decodeURIComponent(field[0]);
field[1] = decodeURIComponent(field[1]);
params[field[0]] = field[1];
}
return params;
}
$(document.links).each(function(i){
if (this.hostname=='www.domain.com' && this.pathname=='/out.php') {
var params = deserialize_query_string(this.search);
if (params.u) {
this.href = u;
}
}
});