How can I save draggable div positions in html - javascript

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';

Related

Maintaining scroll position after hyperlink postback

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

Why does my javascript window.open function read the urls, but not the width and height parameters from an array?

Years ago, I built my website with a lot of flash functionality, though based on html files. I've been working on html/css/javascript alternatives, but got stuck on one last page. It includes a simple (javascript) slide show with backwards and forwards buttons and a clickable image that opens into a customized window. In the Flash version the images are swf files with the following actionscript embedded:
movieclip_inst.onRelease = function():Void {
getURL("javascript:openNewWindow('Photopages/A01La_Jolla1.html', 925, 693)");
}
calling the following javascript function in the head of the html file:
function openNewWindow(page, width, height) {
OpenWin = this.open(page, "Illustrationslideshow", "toolbar=no, menubar=no ,location=no, scrollbars=yes, resizable=yes, statusbar=no, width=" + width + ", height=" + height + ", top=" + (screen.height/2 - height/2) + ", left=" + (screen.width/2 - width/2) + "\"");
}
This opens up the individual html files, that are listed in an external array, like so:
function setupPages() {
var pages = new Array();
pages[0] = 'Photopages/A01La_Jolla1.html', 925, 690;
pages[1] = 'Photopages/A02La_Jolla2.html', 888, 650;
. . .
return pages;
}
This works perfectly with the Flash version, but when I try to apply the function in the body of the html file:
<img src="images/photosforswfs/La_Jolla_01.jpg" id="artwork" />
it will only call up the html image file, but not adhere to the sizes I set. The windows open up in the same size as the originating window or as a tiny square, depending on the browser. Here's the set up of the pages variable in the head of the html document:
var pages = new Array();
pages = setupPages();
The array also contains the images and captions, set up in the same way:
function setupSlides() {
var slides = new Array();
slides[0] = 'images/photosforswfs/La_Jolla_01.jpg';
...
return slides;
}
and
function setupCaptions() {
var captions = new Array();
captions[0] = '<br />Louis Karhn building in La Jolla, CA | 1';
...
return captions;
}
The slide show is set up as follows:
var slides = new Array();
slides = setupSlides();
var captions = new Array();
captions = setupCaptions();
var currentSlideNum = 0;
var numSlides = slides.length;
function previousSlide() {
if (currentSlideNum == 0) {
currentSlideNum = numSlides-1;
} else {
currentSlideNum--;
}
var slideObj = document.getElementById('artwork');
slideObj.src = slides[currentSlideNum];
var captionObj = document.getElementById('caption');
captionObj.innerHTML = captions[currentSlideNum];
}
function nextSlide() {
if (currentSlideNum == numSlides-1) {
currentSlideNum = 0;
} else {
currentSlideNum++;
}
var slideObj = document.getElementById('artwork');
slideObj.src = slides[currentSlideNum];
var captionObj = document.getElementById('caption');
captionObj.innerHTML = captions[currentSlideNum];
}
What I am doing wrong? I am a total newbie, cutting and pasting code rather than writing it. Nothing I tried would fix the problem. Please help!
janeDee
Your pages[0] array position is saving only Photopages/A01La_Jolla1.html and returning the last value (690).
If you want to have all that data in the pages array, you could make it an object or another array:
pages[0] = ['Photopages/A01La_Jolla1.html', 925, 690];
this way you would have ask for pages[0][1] and pages[0][2] to get the sizes.
other way is using an object:
pages[0] = {url:'Photopages/A01La_Jolla1.html', w:925, h:690};
This way you would have to ask for: pages[0].w and pages[0].h
At the end, of course, you'd need to change a bit the call to your function to specify that with is pages[0].w and so on, but that is simple.
openNewWindow(pages[0].url, pages[0].w, pages[0].h);
or you could just send the array item and let the function extract the info from the inside:
function openNewWindow(page) {
var OpenWin = window.open(page.url, "Illustrationslideshow", "toolbar=no, menubar=no ,location=no, scrollbars=yes, resizable=yes, statusbar=no, width=" + page.w+ ", height=" + page.h+ ", top=" + (screen.height/2 - height/2) + ", left=" + (screen.width/2 - width/2) + "\"");
}
openNewWindow(pages[0]);
I used the object variant that was described. In the external js file I changed the existing pages array to the following:
function setupPages() {
var pages = new Array();
pages[0] = {url:'Photopages/A01La_Jolla1.html', w:925, h:690};
pages[1] = {url:'Photopages/A02La_Jolla2.html', w:688, h:918};
...
return pages;
}
and call the function in the link tag like this:
<a href="javascript:void()#" onclick="openNewWindow(pages[currentSlideNum].url, pages[currentSlideNum].w, pages[currentSlideNum].h);">

It is possible to Resize an iframe without reloading the frame?

Hi Stack Overflow Community.
I have a problem. I have a process with an iFrame.
This process have some Javascript to set iFrame height based on iFrame content. I think its not enough, so I decided to make an automatic resize of the iFrame height based on content changes without reloading any iFrame or process. Unfortunately, I tried but was unable to due to doubts. I searched everywhere in Stack Overflow but I didn't found the solution.
Rules:
Auto Height resize in the iFrame.
No reloads in the parent window or iFrame.
No triggers, no Interval.
Just everything automatic.
Window and iFrame are in the same domain.
Could you please help me?
Thanks, and sorry for bad english.
My Actual CODE:
if(document.getElementById("frame") != undefined)
{
var frame = document.getElementById("frame");
$(frame).load(function(){
var frame_height = frame.contentWindow.document.body.scrollHeight + 'px';
frame.setAttribute('style', 'height:' + frame_height + ' !important');
console.log('its this loading?');
contentBasedIframeResize(); //this is worthless, just testing. isn't dynamic right now. need fix.
// As soon as the frame finish the load, this frame height will be based in the frame content
});
function contentBasedIframeResize()
{
var add_button = $(frame).contents().find(".some_obj"); //preparing the trigger
var remove_button = $(frame).contents().find(".some_obj"); //preparing the trigger
if(add_button != undefined)
{
$(add_button).click(function(){
var add_height = frame.contentWindow.document.body.scrollHeight + 'px';
frame.setAttribute('style', 'height:' + add_height + ' !important');
});
}
if(remove_button != undefined)
{
$(remove_button).click(function(){
var remove_height = $("#frame").contents().find("#table_obj").height();
remove_height = parseInt(remove_height) + 100; //hardcoded
frame.setAttribute('style', 'height:' + remove_height + 'px !important');
console.log("its this working v2?");
});
}
}
}
Try this,
function resizeIframe(obj)
{
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
$('iframe').load(function(){
resizeIframe(this);
});

Can't change iframes onload listener in IE9

I have the following code within an external javascript file.
jQuery(function ($) {
//////////////////////UPCOMING EVENTS JSON SERVER START///////////////////////////
var eventList = $("#eventList"); //cache the element
$.getJSON("/JsonControl/Events.json", function (jsonObj) {
val = "";
for (var i = 0; i < jsonObj.events.length; ++i) {
val += "<p>" + jsonObj.events[i].dateMonth + "/" + jsonObj.events[i].dateNumber +
"/" + jsonObj.events[i].dateYear + " - <span id='EL" + i + "' class='link' " +
"onclick=plotEvent(" + i +")>" + jsonObj.events[i].title + "</span></p>";
}
eventList.html(val);
});
//////////////////////UPCOMING EVENTS JSON SERVER END/////////////////////////////
});
function plotEvent(index)
{
$.ajax({
url: "/JsonControl/Events.json",
dataType: 'json',
async: false,
success: function (jsonObj)
{
var eventBox = window.frameElement;
alert("This alert fires in all browsers, including IE9")
eventBox.onload = function ()
{
alert("This alert doesn't fire in IE9.")
window.frameElement.onload = null; // unset it so it only fires once
eventBox = eventBox.contentDocument || eventBox.contentWindow.document;
eventBox.getElementById("title").innerHTML = (jsonObj.events[index].title);
eventBox.getElementById("content").innerHTML = (jsonObj.events[index].explanation);
eventBox.getElementById("dateHolder").innerHTML = (jsonObj.events[index].dateMonth + "-" + jsonObj.events[index].dateNumber + "-" + jsonObj.events[index].dateYear);
};
eventBox.src="/Event htms/Event.htm";
}
});
}
The page that loads this script is in the iframe itself. A very similar function called in a different external js file, from the main page outside of the iframe (for a different but similar purpose) works in all browsers just fine. The only difference is that with this code I have to target the onload of the iframe from within the iframe, instead of just grabbing the iframe by id. I then attempt to change, the onload of said iframe, for use with the next internal iframe page (which is why I need to preserve the json array index [i] when dynamically writing the first iframe page's innerHTML.
Sorry if that was a bit wordy, and/or confusing, but suffice it to say that with using the above-pasted code, I have no problems... except with IE (tried in IE9). I have tried dozens of examples and supposed solutions, but nothing has worked. Using IE9.
Here's what I mean when I say 'it doesn't work in IE9':
This part of the code within plotEvent() doesn't fire:
eventBox.onload = function ()
{
alert("This alert doesn't fire in IE9.")
window.frameElement.onload = null; // unset it so it only fires once
eventBox = eventBox.contentDocument || eventBox.contentWindow.document;
eventBox.getElementById("title").innerHTML = (jsonObj.events[index].title);
eventBox.getElementById("content").innerHTML = (jsonObj.events[index].explanation);
eventBox.getElementById("dateHolder").innerHTML = (jsonObj.events[index].dateMonth + "-" + jsonObj.events[index].dateNumber + "-" + jsonObj.events[index].dateYear);
};
Is there any solution to this problem, or is this sort of thing why iframes aren't used more often (that is, that IE doesn't fully support them)?
Try eventBox.contentWindow.onload or maybe $(eventBox).load(function)

HTML5 video loading time

I am trying to calculate the measure time of html 5 video. I use Javascript to listen to html5 video event loadstart and canplaythrough using:
media.addEventListener('loadstart'getStartTime(){
startTime = new Date().getTime();},
false)
and similar for endTime with event set as canplaythrough to listen.
However I could not get any data.
Can someone please guide me how to measure video load time using Javascript.
Thank you for your response, but the solution is I believe using jQuery; however, I was wondering if it is possible from Javascript. I have attached a copy of my code:
function loadVideo(){
var timeNow = Date.now(), timeStartLoad, timeFinishLoad;
myVideos = new Array();
myVideos[0] = "trailer.mp4";
myVideos[1] = "trailer.ogg";
myVideos[2] = "trailer.m4v";
var videoId = document.getElementById('idForVideo');
var video = document.createElement('video');
for(var i=0; i<myVideos.length; i++){
var source = document.createElement('source');
source.setAttribute('src', myVideos[i]);
video.appendChild(source);
}
video.load();
video.addEventListener('loadstart', function(){
timeStartLoad = Date.now() - timeNow;
}, false);
video.addEventListener('hasenoughdata', function(){
timeFinishLoad = Date.now() - timeStartLoad;
}, false);
idForVideo.appendChild(video);
newDiv = document.getElementById('newDiv');
newDiv.innerHTML = "BodyLoad: " + timeNow + " " + "; Video Load: " + timeStartLoad + "; Video Loaded: " + timeFinishLoad;
//alert(timeStartLoad);
}
However I get undefined for both timestartLoad and timeFinishLoad. My html body has onload method linked to this function.
Your code has some (copy & paste) syntax problems.
var timeInit = Date.now(), timeLoad, timeCanPlay;
$("movie").addEventListener('loadstart', function(){
timeLoad = Date.now();
$("t1").innerHTML = "load: " + (timeLoad - timeInit) + " msecs";
});
$("movie").addEventListener('canplaythrough', function(){
timeCanPlay = Date.now();
$("t2").innerHTML = "canplay: " + (timeCanPlay - timeLoad) + " msecs";
});
$("movie").src = "http://ia600208.us.archive.org/12/items/FarSpeak1935/FarSpeak1935_512kb.mp4";
$("movie").play();
Try out: http://jsfiddle.net/noiv/98xZP/:
Hey, I figured it out.
The reason seems to be due to the fast responsiveness of the browser that it fetches the data before even the event is catched. A solution as provided by opera seems to work. Include the event listener at the inline script and make addEventListener for window object.
More details at:
http://dev.opera.com/articles/view/consistent-event-firing-with-html5-video/
While I can't comment, I have added a fork to the fiddle posted above by #noiv , as the fiddle had some JS errors. Thanks #noiv for putting me on the right direction.
http://jsfiddle.net/truedat101/Gbfj2/7/
$("movie").addEventListener('loadstart', function(){
timeLoad = Date.now();
console.log("loadstart event time: " + timeLoad + ", delta: " + (timeLoad - timeInit));
// alert("loadstart event time: " + timeLoad + ", delta: " + (timeLoad - timeInit));
});
It is worth noting the whatwg is attempting to get some uniformity around video metrics in the browser, so that there will be some common attributes supported by the browser, though it appears already that this work will be split across party lines, with Mozilla supporting their own metrics, Chromium team supporting theirs, and Apple Safari supporting theirs.

Categories