Frame location change bug - javascript

I have successfully changed the location of frames on my page using commands like:
parent.bottomframe.location = 'interstitial.html';.
This one particular call, however, isn't working. I am calling a js function from the 'onclick' of a button in html. This function does most of its work successfully, and also successfully changes the text of my top frame using
parent.topframe.document.getElementById("tutorial").innerHTML = text;
But the bottom frame doesn't change. Could it be that I'm losing permission to change this property? If I put an alert() after the location-change line, I get back the old location, not the new one.
Any ideas?
(Here's the code for this function:)
function GetInterstitial(found_target)
{
parent.topframe.current_trial++;
if (found_target)
{
parent.topframe.correct++;
}
if (parent.topframe.current_trial==parent.topframe.total_trials)
{
UpdateData(parent.topframe.output);
setTimeout(function()
{SendAllData();}, 0
);
parent.topframe.document.getElementById("tutorial").innerHTML = thank_you_text[0]+parent.topframe.correct.toString()+'/'+parent.topframe.total_trials.toString()+thank_you_text[1];
parent.bottomframe.location.href = 'http://urlname..../js/thankyou.html?c='+parent.topframe.userID;
}
else
{
if (found_target)
text = "<p>Great job; you found the hidden number! Now click 'next' to play the next round.</p>";
else
text = "<p>Hmm... it seems you didn't find the hidden number. Click 'next' to play the next round.</p>";
}
setTimeout(function()
{
UpdateData(parent.topframe.output);
},600);
parent.topframe.document.getElementById("tutorial").innerHTML = text; //interstitial_text;
parent.bottomframe.location = 'interstitial.html';
parent.topframe.trial++;
parent.topframe.document.getElementById("nextbutton").style.display="block";
}

Related

EventListener with delay or fire on load of class

I am tweaking the code of a chrome extension to display the content of a page element in the tab title and scroll it fir navigating open ticket tabs easer. As below
// Need to change this, mousemove listener is super harsh on resource
document.addEventListener("mousemove", function() {
// call the banner element
let bannerTextElements = document.getElementsByClassName("cw_BannerView");
// console.log(bannerTextElements);
// console.log(bannerTextElements[0]);
if (bannerTextElements[0]) {
// console.log("ok");
// console.log(bannerTextElements[0].innerHTML);
// Find and get ticket detail
let bannerTextLine = bannerTextElements[0].getElementsByClassName("detailLabel");
// console.log(bannerTextLine);
if (bannerTextLine[0]) {
// console.log(bannerTextLine[0].innerHTML);
// Trim "Service Ticket for cleanness Need to do this for 'Manage' too"
let tickettext = bannerTextLine[0].innerHTML.split("Manage ");
let tickettext1 = bannerTextLine[0].innerHTML.split("Service Ticket ");
// console.log(tickettext[0]);
// console.log(tickettext[1]);
// Set the title equal to everything after "Service Ticket"
if (tickettext1[1]) {
document.title = tickettext1[1];
// now works!! bit clunky though
var documentTitle = tickettext1 + " - ";
(function titleMarquee() {
document.title = documentTitle = documentTitle.substring(1) +
documentTitle.substring(0,1);
setTimeout(titleMarquee, 160);
})();
} else {
// For everything else, just display what's already there
document.title = tickettext1[0];
}
}
}
}, false);
(ignore the appalling indents i promise thats just on this post! )
However, due to the slow page load the only eventlistener i can get to pick the content of the banner text is 'mousemove' which naturally has the negative side effects of A. Firing infinite times as you view the page and also resetting the scroll to the start as you mouse over.
document.OnLoad and window.onload just stops this working and it loads the default tab title
Is there a way to get onLoad to run after an arbitrary delay, say 10s or to check to make sure that the classname cw_bannerview is loaded up and populate with the ticket title?

HTML javascript bookmark user viewing position

I have a html webpage. It contains a very long text passage.
User can use internet browser to read the passage. Since the passage is long, users need to scroll the page to read the whole passage.
I would like to add a floating box button for user to click. After clicking the button, I can capture the current viewing portion of the passage.
So that users can log in later and continue reading.
I think I need to add some javascript, but after hours of online searching, I failed to find relevant information.
Please kindly suggest the possible solution to do so?
Use a position:fixed box/button. Clicking it stores (or updates, if it already exists) a localStorage item or cookie with the current position. On page load, if that item exists, ask the user if they want to return to that spot.
There are two ways of doing this:
Save position as a pixel value. This works perfectly if the user's display will not change size (switching computers, switching monitors, changing screen resolution setting, etc.). However, if any of those changes do occur, the absolute pixel value of the saved position is not consistent with the position on the page.
Demo. To run: click "Save position", scroll anywhere, then reload the page.
Save position as a percentage of total height. This works exactly as solution (1), but handles all cases in which screen size changes as well. (Use this one.) The code provided below pertains to this solution.
Demo. To run: click "Save position"; change the width of the "Result" quadrant; without changing any code, click "Run" again.
The saved item is removed regardless of the user's choice (to return to the last spot or not), so that the prompt doesn't show up every time the page is reloaded (which can get annoying).
This is pure JS; it's very modular; it demonstrates simple usage of localStorage and falls back gracefully to cookies.
HTML
<div id="save">
<button id="saveButton">Save position</button>
<span id="saved">Saved!</span>
</div>
<div id="content">
<!-- Disgustingly long content -->
</div>
CSS
#save {
position:fixed;
top:30px;
left:10px;
width:20%;
}
#saved {
visibility:hidden;
color:green;
}
#content {
width:60%;
margin:auto;
}
JS
function checkStorageSupport() {
var test = "test";
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
function getTotalHeight() {
return document.body.clientHeight;
}
function getSavedPercent() {
var percent = storageSupported ? loadFromStorage() : loadFromCookie();
return (percent == null || percent == "") ? 0 : percent;
}
/******* Save *******/
function saveInStorage() {
localStorage.setItem("scrollPercent", (document.documentElement.scrollTop / getTotalHeight()));
}
function saveCookie() {
var expDate = new Date();
expDate.setDate(expDate.getDate() + 7); // start over if it's been more than ___ days
document.cookie = "scrollPercent=" + (document.documentElement.scrollTop / getTotalHeight())
+ "; " + expDate;
}
/******* Load *******/
function loadFromStorage() {
return localStorage.getItem("scrollPercent");
}
function loadFromCookie() {
return document.cookie.replace(/(?:(?:^|.*;\s*)scrollPercent\s*\=\s*([^;]*).*$)|^.*$/, "$1");
}
/******* Remove *******/
function removeFromStorage() {
localStorage.removeItem("scrollPercent");
}
function removeCookie() {
document.cookie = "scrollPercent=''";
}
/******* Handler *******/
var saveButton = document.getElementById("saveButton"),
saved = document.getElementById("saved");
saveButton.onclick = function() {
storageSupported ? saveInStorage() : saveCookie();
saved.style.visibility = "visible";
setTimeout(function() {
saved.style.visibility = "hidden";
}, 1500);
};
/******* Logic *******/
var storageSupported = checkStorageSupport(),
percent = getSavedPercent();
if (percent > 0) {
if (confirm("Would you like to continue reading where you left off?")) {
document.documentElement.scrollTop = percent * getTotalHeight();
}
storageSupported ? removeFromStorage() : removeCookie();
}
Note: to get back to the code that produces solution (1), copy the code from that demo. In the case JSFiddle goes down, here are manual instructions:
Remove every instance of / getTotalHeight() in a "Save" function
In the "Logic" section, replace position * getTotalHeight() with position
Remove getTotalHeight(), since it's not used
Replace instances of "percent" with "position" to be more semantically accurate
Basic idea is..
create a floating bookmark button on the page like:
#mybookmark{
position: fixed;
top:30px;
right:0;
}
Now in jquery.. retrieve the position of this floating bookmark when clicked on it..
$('#mybookmark').click(function(){
var bookmark_loc = $('#mybookmark').offset().top();
});
Store this bookmark_loc data in your preferred storage for the user.
then when they clicks on a button, you can scroll to the stored offset value in your storage.. in jquery
$('#scroll_to_bookmark').click(function{
var bookmark_loc = //Fetch bookmark
$('body').animate({ scrollTop: bookmark_loc; });
});

building a Jquery Tool slider like yahoo.com slider details

Hi im trying to achieve a "news slider" like the one you can see in yahoo.com... I almost have the 100% of the code.. (if you want to compare them here is my code http://jsfiddle.net/PcAwU/1/)
what is missing in my code , (forget about design) is that , In my slider you have to clic on each item, i tried to replace Onclick for Hover on the javascript, it worked, but the fisrt image on the gallery stop working, so when you just open the slider, you see a missing image.
Other point.. also very important, in yahoo.com after "x seconds" the slider goes to the next item, and so on ... all the Thumnails are gruped 4 by for 4, (in mine 5 by 5, thats ok) ... after pass all the 4 items, it go to the next bloc..
HOW CAN I ACHIEVE THAT!!. I really looked into the API, everything, really im lost, i hope someone can help me. cause im really lost in here.
Thanks
Here is the script
$(function() {
var root = $(".scrollable").scrollable({circular: false}).autoscroll({ autoplay: true });
$(".items img").click(function() {
// see if same thumb is being clicked
if ($(this).hasClass("active")) { return; }
// calclulate large image's URL based on the thumbnail URL (flickr specific)
var url = $(this).attr("src").replace("_t", "");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").fadeTo("medium", 0.5);
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", url);
};
// begin loading the image from www.flickr.com
img.src = url;
// activate item
$(".items img").removeClass("active");
$(this).addClass("active");
// when page loads simulate a "click" on the first image
}).filter(":first").click();
// provide scrollable API for the action buttons
window.api = root.data("scrollable");
});
function toggle(el){
if(el.className!="play")
{
el.className="play";
el.src='images/play.png';
api.pause();
}
else if(el.className=="play")
{
el.className="pause";
el.src='images/pause.png';
api.play();
}
return false;
}
To fix the hover problem you need to make some quick changes: Change the click to a on(..) similar to just hover(..) just the new standard.
$(".items img").on("hover",function() {
....
Then You need to update the bottom click event to mouse over to simulate a hover effect. Trigger is a comman function to use to trigger some event.
}).filter(":first").trigger("mouseover");
jSFiddle: http://jsfiddle.net/PcAwU/2/
Now to have a play feature, you need a counter/ and a set interval like so:
var count = 1;
setInterval(function(){
count++; // add to the counter
if($(".items img").eq(count).length != 0){ // eq(.. select by index [0],[1]..
$(".items img").eq(count).trigger("mouseover");
} else count = 0; //reset counter
},1000);
This will go show new images every 1 second (1000 = 1sec), you can change this and manipulate it to your liking.
jSFiddle: http://jsfiddle.net/PcAwU/3/
If you want to hover the active image, you need to do so with the css() or the addClass() functions. But You have done this already, All we have to do is a simple css change:
.scrollable .active {
....
border-bottom:3px solid skyblue;
Here is the new update jSFilde: http://jsfiddle.net/PcAwU/4/

display message javascript while a calculation is being made

I have been looking around and I cannot seem to figure out how to do this, although it seems like it would be very simple.(mobile development)
What I am trying to do is display a message (kind of like an alert, but not an alert, more like a dialog) while a calculation is being made. Simply like a Loading please wait. I want the message to appear and stay there while the calculation is being done and then be removed. I just cannot seem to find a proper way of doing this.
The submit button is pressed and first checks to make sure all the forms are filled out then it should show the message, it does the calculation, then hides the message.
Here is the Calculation function.
function scpdResults(form) {
//call all of the "choice" functions here
//otherwise, when the page is refreshed, the pulldown might not match the variable
//this shouldn't be a problem, but this is the defensive way to code it
choiceVoltage(form);
choiceMotorRatingVal(form);
getMotorRatingType();
getProduct();
getConnection();
getDisconnect();
getDisclaimer();
getMotorType();
//restore these fields to their default values every time submit is clicked
//this puts the results table into a known state
//it is also used in error checking in the populateResults function
document.getElementById('results').innerHTML = "Results:";
document.getElementById('fuse_cb_sel').innerHTML = "Fuse/CB 1:";
document.getElementById('fuse_cb_sel_2').innerHTML = "Fuse/CB 2:";
document.getElementById('fuse_cb_result').innerHTML = "(result1)";
document.getElementById('fuse_cb_res_2').innerHTML = "(result2)";
document.getElementById('sccr_2').innerHTML = "<b>Fault Rating:</b>";
document.getElementById('sccr_result').innerHTML = "(result)";
document.getElementById('sccr_result_2').innerHTML = "(result)";
document.getElementById('contactor_result').innerHTML = "(result)";
document.getElementById('controller_result').innerHTML = "(result)";
//Make sure something has been selected for each variable
if (product === "Choose an Option." || product === "") {
alert("You must select a value for every field. Select a Value for Product");
**************BLAH************
} else {
//valid entries, so jump to results table
document.location.href = '#results_a';
******This is where the message should start being displayed***********
document.getElementById('motor_result').innerHTML = motorRatingVal + " " + motorRatingType;
document.getElementById('voltage_res_2').innerHTML = voltage + " V";
document.getElementById('product_res_2').innerHTML = product;
document.getElementById('connection_res_2').innerHTML = connection;
document.getElementById('disconnect_res_2').innerHTML = disconnect;
if (BLAH) {
}
else {
}
populateResults();
document.getElementById('CalculatedResults').style.display = "block";
} //end massive else statement that ensures all fields have values
*****Close out of the Loading message********
} //scpd results
Thank you all for your time, it is greatly appreciated
It is a good idea to separate your display code from the calculation code. It should roughly look like this
displayDialog();
makeCalculation();
closeDialog();
If you are having trouble with any of those steps, please add it to your question.
Computers are fast. Really fast. Most modern computers can do several billion instructions per second. Therefore, I'm fairly certain you can rely on a a setTimeout function to fire around 1000ms to be sufficient to show a loading message.
if (product === "Choose an Option." || product === "") {
/* ... */
} else {
/* ... */
var loader = document.getElementById('loader');
loader.style.display = 'block';
window.setTimeout(function() {
loader.style.display = 'none';
document.getElementById('CalculatedResults').style.display = "block";
}, 1000);
}
<div id="loader" style="display: none;">Please wait while we calculate.</div>
You need to give the UI main thread a chance to render your message before starting your calculation.
This is often done like this:
showMessage();
setTimeout(function() {
doCalculation();
cleanUp()
}, 0);
Using the timer allows the code to fall through into the event loop, update the UI, and then start up the calculation.
You're already using a section to pop up a "results" page -- why not pop up a "calculating" page?
Really, there are 4,000,000 different ways of tackling this problem, but why not try writing a "displayCalculatingMessage" function and a "removeCalculatingMessage" function, if you don't want to get all object-oriented on such a simple thing.
function displayCalculatingMessage () {
var submit_button = getSubmitButton();
submit_button.disabled = true;
// optionally get all inputs and disable those, as well
// now, you can either do something like pop up another hidden div,
// that has the loading message in it...
// or you could do something like:
var loading_span = document.createElement("span");
loading_span.id = "loading-message";
loading_span.innerText = "working...";
submit_button.parentElement.replaceChild(loading_span, submit_button);
}
function removeCalculatingMessage () {
var submit_button = getSubmitButton(),
loading_span = document.getElementById("loading-message");
submit_button.disabled = false;
loading_span.parentElement.replaceChild(submit_button, loading_span);
// and then reenable any other disabled elements, et cetera.
// then bring up your results div...
// ...or bring up your results div and do this after
}
There are a billion ways of accomplishing this, it all comes down to how you want it to appear to the user -- WHAT you want to have happen.

change image src with javascript not working

Here is my code
function playPause(){
movie = document.getElementById('movieEMBED');
icon = document.getElementById('playPauseIcon');
var isPlaying;
isPlaying = movie.GetRate();
if (!isPlaying){
movie.Play();
icon.setAttribute('src', "images/pausebutton.png");
}
else {
movie.Stop();
icon.setAttribute('src', "images/playbutton.png");
}
}
in the html:
<input type="image" id="playPauseIcon" src="images/playbutton.png" width=30px onClick='playPause()'></input>
Any ideas as to why the picture does not switch between the pause and play button when I click the button?
I'm guessing it's because your movie is playing. The else of the if block sets the src to the same value:
if (!isPlaying){
movie.Play();
icon.setAttribute('src', "images/pausebutton.png");
}
else {
movie.Stop();
icon.setAttribute('src', "images/playbutton.png"); // <---- no change
}
Just to be sure that your code is right, which it appears to be, I would change the function to this:
function playPause(){
var icon = document.getElementById('playPauseIcon');
icon.setAttribute('src', "images/pausebutton.png");
}
and then slowly add in your movie code
As far as I can see, your code is fine. Are you sure movie.GetRate() returns different values and you're passing by both paths of the 'if' correctly? I would think movie.GetRate() is returning always the same value so you never set the src attribute to a different image.

Categories