Maintaining scroll position after hyperlink postback - javascript

I have tried numerious different approaches to my problem, but none of them seem to work out. I basically activate and deactivate users using a asp.net hyperlink and the problem is as soon as you do that, the page scrolls back up because of the postback it creates, so it will be annoying to scroll back down if you have a list of 1000 users. Here is the code iv'e been trying out without success!
// I use this variable for navigating the url for my hyperlink
var toggleUrl = "AdminListUsers.aspx?column=" + (IsClicked.FirstOrDefault().Key ?? "Name") + "&direc=" + (IsClicked.FirstOrDefault().Value) + "&a=chstat&q=" + id.ToString() + "&d=" + disabled + "&z=" + Server.UrlEncode(txtSearchFor.Text);
var hl = new HyperLink(); //These hyperlinks are the same
hl.Text = status;
hl.Style.Add(HtmlTextWriterStyle.Color, (disabled ? "red" : "green"));
hl.NavigateUrl = toggleUrl;
hl.Attributes.Add("onclick", "saveScroll(this);return true;");
cell.Controls.Add(hl);
tr.Cells.Add(cell);
cell = new TableCell();
cell.Width = new Unit("10%");
cell.Controls.Add(new LiteralControl("<nobr>"));
var linkbtn = new HyperLink //These hyperlinks are the same
{
//Here as you can see are my attributes for the hyperlink
NavigateUrl = toggleUrl,
Width = 16,
Height = 16,
CssClass = disabled ? "user-status-disabled" : "user-status-enabled"
};
linkbtn.Attributes.Add("id", "aButton_" + id);
ScriptManager.RegisterStartupScript(Page, typeof(Page), "ScrollToADiv", "setTimeout(scrollToDiv, 1);", true); // Not working
linkbtn.Attributes.Add("onclick", "window.scrollTo(0, location.hash);"); // Not working either
cell.Controls.Add(linkbtn);
cell.Controls.Add(new LiteralControl(" "));

As per my understanding, you could set the MaintainScrollPositionOnPostback to true in any of the below three ways.
Web.config Level => pages maintainScrollPositionOnPostBack="true" />
Page Level => <%# Page MaintainScrollPositionOnPostback="true" %>
Code Level => Page.MaintainScrollPositionOnPostBack = true;
Hope this Helps!!
EDIT
Code help for the comment below (assuming jQuery is being used):
$(".user-status-enabled").on("click", function() {
var $this = $(this);
var scrollPosition = $this.scrollTop();
$this.attr("href", $this.attr("href") + "&scrollPosition=" + scrollPosition);
});
And on the target screen, access this scrollPosition from Query String and set the scroll position on dom Ready

Related

How can I save draggable div positions in html

I'm a newbie in html and javascripts, and trying to save my draggable div positions after clicking save button in my web application. my question is little bit different with others that I'm using Websocket for getting data
Here is my draggable divs which is creating from websocket in javascript code
function WebSocket(){
if ("WebSocket" in window){
var channel = "hello";
var socket = io.connect("my socket address here");
socket.on(channel, function (d) {
var data = JSON.parse(d);
console.log(channel + " : " + d);
var theDiv = document.getElementById(data.node_info[1].info.mac);
if(theDiv == null) {
var divTag = document.createElement("div");
divTag.id = data.node_info[1].info.mac; //"drag1"
divTag.className = "draggable js-drag";
divTag.innerHTML = data.node_info[1].info.mac;
document.getElementsByTagName('body')[0].appendChild(divTag);
//document.getElementsByName('scroll_div')[0].appendChild(divTag);
//$('#'+data.node_info[1].info.mac).load('#'+data.node_info[1].info.mac);
}
});
socket.on('crc_err', function(packet){
console.log("crc_err : " + packet);
});
socket.on('type_err', function(packet){
console.log("type_err : " + packet);
});
} else{
// The browser doesn't support WebSocket
// alert("WebSocket NOT supported by your Browser!");
}
}
I created divTags with id, className, innerHTML and each of them shows mac addresses and put them in the body of html.
Also, I want those draggable divs is positioned in same places as last time when users revisit my web app.
How should I do and any suggestions here??
Thanks in advance.
p.s If you need my css code or more code of html I can EDIT
Use localStorage
To save
localStorage.setItem(divTag.id + '-X', leftPosition);
localStorage.setItem(divTag.id + '-Y', topPosition);
To load back
divTag.style.left = localStorage.getItem(divTag.id + '-X') + 'px';
divTag.style.top = localStorage.getItem(divTag.id + '-Y') + 'px';

Targeting tabs on page with direct URL link breaks URL on tab click

I'm trying to create a tabbed area within my page. The tabs navigate hidden areas with out leaving the page. I also want to be able to link to an area with in the page. It's working except when you click the menu as well as revealing the hidden area it's rewriting the URL with only the tab extension and therefor breaking the link of the URL. So someone trying to share the link would not know the format..
I'm using this code https://css-tricks.com/examples/OrganicTabsReplaceState which I see no problem with.
You can see a live demo with my issue here: http://bit.ly/1IP1ST4
Clicking the tab is removing:
/products/eurorack-modules/waveform-modifiers/reactive-shaper/
And replacing it with ?tab=mytabname
It should be simply adding it. I'm struggling to work out why..?
If you inspect the source of the first link you provided, you will see that the tabs contain links like this:
Featured
That's an in-page link. You should use #'s for in page links. The reason the whole url is being replaced is because it's interpreting the href as a new url to go to. #'s look inside the current page.
This version of organictabs.jquery.js got it working in the end seemed to be an issue with the way it treated the URL.. Maybe this will help someone else.
// IIFE
(function($) {
// Define Plugin
$.organicTabs = function(el, options) {
// JavaScript native version of this
var base = this;
// jQuery version of this
base.$el = $(el);
// Navigation for current selector passed to plugin
base.$nav = base.$el.find(".nav");
// Returns the fragment identifier of the given URL
function getFragmentIdentifier(url) {
if(url && url.match && url.match(/#(.*)/)) {
return RegExp.$1;
}
}
// Remove the query string from the url
function noQueryString(url) {
if(url && url.match && url.match(/^([^\?]*)\??/)) {
return RegExp.$1;
}
}
// Runs once when plugin called
base.init = function() {
// Pull in arguments
base.options = $.extend({},$.organicTabs.defaultOptions, options);
// Accessible hiding fix (hmmm, re-look at this, screen readers still run JS)
$(".hide").css({
"position": "relative",
"top": 0,
"left": 0,
"display": "none"
});
// When navigation tab is clicked...
base.$nav.delegate("a", "click", function(e) {
// no hash links
e.preventDefault();
// Figure out current list via CSS class
var curList = getFragmentIdentifier(base.$el.find("a.current").attr("href")),
// List moving to
$newList = $(this),
// Figure out ID of new list
listID = getFragmentIdentifier($newList.attr("href")),
// Set outer wrapper height to (static) height of current inner list
$allListWrap = base.$el.find(".list-wrap"),
curListHeight = $allListWrap.height();
$allListWrap.height(curListHeight);
if ((listID != curList) && ( base.$el.find(":animated").length == 0)) {
// Fade out current list
base.$el.find("#"+curList).fadeOut(base.options.speed, function() {
// Fade in new list on callback
base.$el.find("#"+listID).fadeIn(base.options.speed);
// Adjust outer wrapper to fit new list snuggly
var newHeight = base.$el.find("#"+listID).height();
$allListWrap.animate({
height: newHeight
}, base.options.speed);
// Remove highlighting - Add to just-clicked tab
base.$el.find(".nav li a").removeClass("current");
$newList.addClass("current");
// Change window location to add URL params
if (window.history && history.pushState) {
// NOTE: doesn't take into account existing params
history.replaceState("", "", noQueryString(window.location.href) + "?" + base.options.param + "=" + listID);
}
});
}
});
var queryString = {};
window.location.href.replace(
new RegExp("([^?=&]+)(=([^&]*))?", "g"),
function($0, $1, $2, $3) { queryString[$1] = $3; }
);
if (queryString[base.options.param]) {
var tab = $("a[href='#" + queryString[base.options.param] + "']");
tab
.closest(".nav")
.find("a")
.removeClass("current")
.end()
.next(".list-wrap")
.find("ul")
.hide();
tab.addClass("current");
$("#" + queryString[base.options.param]).show();
};
};
base.init();
};
$.organicTabs.defaultOptions = {
"speed": 300,
"param": "tab"
};
$.fn.organicTabs = function(options) {
return this.each(function() {
(new $.organicTabs(this, options));
});
};
})(jQuery);

Reload Parent Window without POST

I am trying to reload a parent window (same domain) with javascript from within an iframe.
window.parent.location.href = window.parent.location.href;
does not work here for some reason (no javascript errors).
I don't believe it is a problem with same origin policy, as the following works:
window.parent.location.reload();
The problem with this option is if the last request was a POST, it gets reloaded as POST.
Any ideas why the first option wouldn't work? Otherwise, is there another method that will reload the page without resubmitting any form data (e.g. perform a fresh GET request to the parent page URL)?
I have also tried:
top.frames.location.href = top.frames.location.href;
window.opener.location.href = window.opener.location.href
and various other iterations.
I tried this code:
window.location.href = window.location.href;
in an ordinary page (no frames) and it had no effect either. The browser must detect that it is the same URL being displayed and conclude that no action needs to be taken.
What you can do is add a dummy GET parameter and change it to force the browser to reload. The first load might look like this (with POST data included, not shown here of course):
http://www.example.com/page.html?a=1&b=2&dummy=32843493294348
Then to reload:
var dummy = Math.floor(Math.random() * 100000000000000);
window.parent.location.href = window.parent.location.href.replace(/dummy=[0-9]+/, "dummy=" + dummy);
Phari's answer worked for me, with a few adjustments to fit my use case:
var rdm = Math.floor(Math.random() * 100000000000000);
var url = window.parent.location.href;
if (url.indexOf("rdm") > 0) {
window.parent.location.href = url.replace(/rdm=[0-9]+/, "rdm=" + rdm);
} else {
var hsh = "";
if (url.indexOf("#") > 0) {
hash = "#" + url.split('#')[1];
url = url.split('#')[0];
}
if (url.indexOf("?") > 0) {
url = url + "&rdm=" + rdm + hsh;
} else {
url = url + "?rdm=" + rdm + hsh;
}
window.parent.location.href = url;
}
I'm sure this could be more efficient, but works ok.

Dynamically modify the url using javascript

I would like to change the url of the page when the user select another page to visit. The url is dynamically replace the original one.
eg.
If user visit page 1 , the url will be book.html?page=1
If page 30 then book.html?page=30 and so on.
However, when I change the link using javascript, it falls into a infinite loop.
It seems I keep visit->change link ->visit ->change link->.... How to fix this problem?
eg. When the link change, don't access the page.
var currURL = $(location).attr('href');
var index = currURL.indexOf('?');
currURL = currURL.substring(0, index != -1 ? index : currURL.length);
// fall into loop
$(location).attr('href', currURL + '?page=' + pageNo);
You can do this pretty easily with just standard javascript.
if(location.href.indexOf('?') !== -1 && location.href.indexof('?page=') === -1)
{
var urlArray = location.href.split('?');
var newURL = urlArray[0] + "?page=" + urlArray[1];
location.href = newURL;
}

popup in a popup, second popup has no focus?

Ok I know this is going to sound weird but it is what the client wants. I am working within a popup and when a user clicks on a datagrid cell within a certain column it will popup a html table with data. I have the second popup to display but it does not get focus. This is currently the code I am using to create the second popup. Any help to get the focus on this second popup would be great.
function onCellClick() {
var cmGrid = igtbl_getGridById("countermeasureDetailsGrid");
var cmCellID = cmGrid.ActiveCell.split("_");
if (cmCellID[3] === "3") {
var countermeasureID = igtbl_getCellById("countermeasureDetailsGrid_rc_" + cmCellID[2] + "_0").getValue();
var recordType = igtbl_getCellById("countermeasureDetailsGrid_rc_" + cmCellID[2] + "_4").getValue();
_crfPopupWindow = new crfPopupWindow(countermeasureID, recordType);
_crfPopupWindow.open();
_crfPopupWindow.focus();
}
}
function crfPopupWindow(countermeasureID, recordType) {
var crfPopup = new WindowDef();
crfPopup.target = "CRF_Popup.aspx?countermeasureID=" + countermeasureID + "&" + "recordType=" + recordType;
crfPopup.windowName = "CRFPopup";
crfPopup.toolBar = "no";
crfPopup.resizable = "yes";
crfPopup.scrollbars = "yes";
crfPopup.location = "yes";
crfPopup.width = 350;
crfPopup.height = 400;
return crfPopup;
}
EDIT: Solution
<script type="text/javascript" language="javascript">
function init() {
window.focus();
}
</script>
Have you checked that the 2nd popup has higher z-index CSS property?
First popup can have z-index of, say, 1000, but the second should have then 1001.
window.focus on page load This works

Categories