Javascript: Object not accessible after closing parent window - javascript

So I have a parent window who is opening itself to a new window (just to remove the status bar, toolbar, others). After closing the parent window, the passed variable return blank string. Sometimes it returns this error message: "The remote server machine does not exist or is unavailable." I really need to access this variable even after closing the parent window. Any suggestions?
var _env = {};
$(window).load(function()
{
/**
*
* If initialization was not yet performed, start the initialization.
* Otherwise, show application.
*
**/
if (window.opener)
{
/* Start transition to the new window */
window.blur();
_env = window.opener._env;
console.log(_env["title"]);
/* Show system */
window.opener.close();
window.focus();
console.log(_env["title"]); // Returns blank
}
else
{
/* Some process manipulating the '_env' variable */
/* .... */
/* .... */
window.open("./index.html", _env["title"], "directories=0, menubar=0, toolbar=0, titlebar=0, resizable=1, width=" + _env["winWidth"] + ", height=" + _env["winHeight"]);
window.focus();
window.open("","_self", ""); // To prevent prompt on closing..
}
});

You can convert the object to JSON, and set window.location.href to it. You can then extract it when you need the data, and there won't be any issues with references because you're creating a new object.

Related

Is there a way to watch screenX and screenY positions and have a method run when they change?

I am trying to run a method whenever the screenX or screenY position of a rendered window changes. I have set up a a default value for these positions in my data section here:
data() {
return {
initialX: window.screenX,
initialY: window.screenY
};
},
I have computed properties here:
currentPopupX() {
return window.screenX;
},
currentPopupY() {
return window.screenY;
}
},
Finally, I have a watch set up here:
watch: {
currentPopupX() {
if (this.currentPopupX !== this.initialX) {
movePopup(this.popup, this.currentPopupX, this.currentPopupY);
}
},
currentPopupY() {
if (this.currentPopupY !== this.initialY) {
movePopup(this.popup, this.currentPopupX, this.currentPopupY);
}
},
However the computed property seems to only return on initial render and does not update after that. Is there something I am missing?
I have tried comparing initial data to computed properties in the watch expecting for the method to be executed on change, however it never changes.
Note:
The rendered window is a popup notification. A user wants to drag that notification to a new location (currently it renders in the center of the screen) and have that popup render in the position they dragged it to the next time it is rendered. For additional context, I'm trying to grab the new positions to pass them along to an IPC event.
At my opinion, you have to use an interval to detect the browser position since there's no window move event.
if the browser position.x or the browser position.y change, you may dispatch a custom event.
The event here when you move the window will change the color of the text from black to red.
const event = new CustomEvent("browserMove",{ detail: "browserPosition" });
window.addEventListener("browserMove", onBrowserMove);
let moveTimer=null;
let content=null;
let oldX = 0;
let oldY = 0;
document.addEventListener("DOMContentLoaded",onReady);
function onReady(e){
content = document.getElementById("content");
oldX = window.screenX;
oldY = window.screenY;
moveTimer = setInterval(detectBrowserMove,200);
}
function detectBrowserMove(){
let r = browserPosition();
if(r.x !== oldX || r.y !== oldY){
// dispatch an event here
window.dispatchEvent(event);
oldX = window.screenX;
oldY = window.screenY;
}
content.innerHTML = ("browser.x = " + r.x + ", browser.y = " + r.y);
}
function browserPosition() {
let position={};
position = {x:window.screenX, y:window.screenY};
return(position);
}
function onBrowserMove(e){
// write your code here
let x = window.screenX;
let y = window.screenY;
content.style.color="#ff0000";
}
<div id="content">
</div>
If I catch your problem correctly, you are saying that-
A notification window will open in the center by default. The user can
drag it anywhere and when next time the notification window will appear, it should pop up at the position where the user last dragged it.
If we take the problem in some other way, you need the last dragged position of the window to send to the API for the next time opening. So, instead of checking the window's position every time why not check for only the last/latest position before it closes?
What I mean is-
Let the notification window open.
Attach a unload listener to it.
Drag it anywhere you want multiple times.
When the window is about to close, look into the listener, and grab the latest position.
Here is how you can do it in Vue-
Create a window data variable in your Vue and assign your newly opened window object to it-
data() {
return {
// Save notification window object to this data property
vue_window: null;
}
}
Apply a watcher that when vue_window has some value, set a listener to it-
watch: {
vue_window(newVal) {
// Only if vue_window variable has some value
if (newVal) {
// this will fire when the window is about to close
newVal.onunload = () => {
// Here are the latest screen positions of the window
console.log(this.vue_window.screenX, this.vue_window.screenY);
};
}
},
},
That's it. When the window will be about to close, you will have the last and latest position of the window which you can save wherever you want.
Here is the demo of this logic- CodeSandBox Link
I couldn't create a snippet because the window is not opening in the snippet environment. I will add the snippet if found any solution to work with the window obj.

Returning the value of a slider from a web page to a program on change of slider

I am trying to program a ESP32 to control the LED brightness using a slider and have been using some bits cobbled together from https://randomnerdtutorials.com/esp32-servo-motor-web-server-arduino-ide/ and https://randomnerdtutorials.com/esp32-pwm-arduino-ide/
So far I am able to get the ESP32 to connect to my network, display the slider and its value and, when the slider is changed, set the PWM to set the LED brightness.
The downside is that although I can get the slider value to be displayed in the browser while it is being changed the bit that gets me the value of the slider only runs when I release the mouse button. So instead of a slider controlling the LED in realtime I get a slider that sets the PWM value in jumps.
What I want to do is have the LED brightness represent the value on the slider as the slider is changed (before the mouse button is released).
I've tried with oninput and onchange but not had any luck. This isn't helped by my somewhat lacking skills in HTML.
Any pointers anyone could give me would be really appreciated.
My code is below:-
#include <WiFi.h>
/* Web server initialisation stuff */
/* Set the network credentials to connect to */
const char* ssid = "MySID";
const char* password = "MySIDPassword";
/* Create a server instance on port 80 (http) */
WiFiServer server(80);
/* Create a variable to store the HTTP request */
String header;
/* Decode HTTP GET value */
String valueString = String(5);
int pos1 = 0;
int pos2 = 0;
/* LED initialisation stuff */
const byte led_pin = 2;
int intBbrightness = 0;
void setup() {
/* Set the serial speed */
Serial.begin(115200);
/* Set up the LED Pin */
ledcAttachPin (led_pin, 0);
/* Set the initial PWM value, the frequency and the nummer of bits for resolution */
ledcSetup(0,5000,8);
/* Connect to Wi-Fi network with SSID and password */
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
/* Print local IP address and start web server */
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop() {
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
/* if the current line is blank, you got two newline characters in a row.
that's the end of the client HTTP request, so send a response: */
if (currentLine.length() == 0) {
/* HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
and a content-type so the client knows what's coming, then a blank line: */
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
/* Display the HTML web page */
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
/* CSS to style the slider */
client.println("<style>body { text-align: center; font-family: \"Trebuchet MS\", Arial; margin-left:auto; margin-right:auto;}");
client.println(".slider { width: 300px; }</style>");
client.println("<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>");
/* Web Page */
/* Give the page a header here */
client.println("</head><body><h1>ESP32 with Servo</h1>");
/* Show the slider here */
client.println("<p>Position: <span id=\"servoPos\"></span></p>");
client.println("<input type=\"range\" min=\"0\" max=\"256\" class=\"slider\" id=\"servoSlider\" onchange=\"servo(this.value)\" value=\""+valueString+"\"/>");
/* Javascript for the slider */
client.println("<script>var slider = document.getElementById(\"servoSlider\");");
client.println("var servoP = document.getElementById(\"servoPos\"); servoP.innerHTML = slider.value;");
client.println("slider.oninput = function() { slider.value = this.value; servoP.innerHTML = this.value; }");
client.println("$.ajaxSetup({timeout:1000}); function servo(pos) { ");
client.println("$.get(\"/?value=\" + pos + \"&\"); {Connection: close};}</script>");
client.println("</body></html>");
/*GET /?value=180& HTTP/1.1 */
if(header.indexOf("GET /?value=")>=0) {
pos1 = header.indexOf('=');
pos2 = header.indexOf('&');
valueString = header.substring(pos1+1, pos2);
/* Set the brightness of the LED based on the slider */
ledcWrite(0,valueString.toInt());
Serial.println(valueString);
}
/* The HTTP response ends with another blank line */
client.println();
/* Break out of the while loop */
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
/* Clear the header variable */
header = "";
/* Close the connection */
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
If you want update the brightness on your code from a webpage, you have to use onchange.
This is the only way to update in "realtime".
I do not see your updateBrightness function in your code. You say, you can change it if you release the slider. But how, if there is no code to change it?
If you change the slider, you need to call the ESP with a new page. And to listen on this page, you have to add this to your setup code: server.on("/slider", handleSliderChange); for example.
Why will it not work even if you use onchange() ?
It will not work, because a HTML will generate 1000 requestes each second with the new value. Your ESP will never be able to handle so much requests.
What you have to do is to start ONLY 1 request to your ESP and wait, until the ESP answered. If, after the answer was received, the slider value changed, you can send the next value, until the slider value does not change anymore.
If, during the transmission of the new value, the slider calls onchange, you have just to save the new slider value, without send the request to the ESP.

Mozilla Firefox Add-on Android - Page Action not working

I have been working on this issue for a few hours now and can't seem to find any good sources on how to implement page action on android. Just the same one, Differences_between_desktop_and_Android.
I hooked up my app to the web debugger in firefox get no errors. I tried to manually call some functions and none were defined. I could be doing it wrong, but it works on my PC version of Firefox.
I created some context menu items at the top of my BG script. I'm not sure if that would affect the execution of the script on android.
ReferenceError: browser is not defined[Learn More] debugger eval code:1:1
Below is the code the creates the Page Action which is included in my Background.js.
/* *********** */
/* Page Action */
/* *********** */
const TITLE_APPLY = "Stack Open";
const TITLE_REMOVE = "Stack Closed";
const APPLICABLE_PROTOCOLS = ["http:", "https:"];
/*
Based on the current title, Update the page action's title and icon to reflect its state.
*/
function toggleT(tab) {
function gotTitle(title) {
if (title === TITLE_APPLY) {
console.log(tab.id);
//browser.pageAction.setIcon({tabId: tab.id, path: "pressed.svg"});
browser.pageAction.setTitle({tabId: tab.id, title: TITLE_REMOVE});
} else {
//browser.pageAction.setIcon({tabId: tab.id, path: "nPressed.svg"});
browser.pageAction.setTitle({tabId: tab.id, title: TITLE_APPLY});
}
}
var gettingTitle = browser.pageAction.getTitle({tabId: tab.id});
gettingTitle.then(gotTitle);
}
/*
Returns true only if the URL's protocol is in APPLICABLE_PROTOCOLS.
*/
function protocolIsApplicable(url) {
var anchor = document.createElement('a');
anchor.href = url;
return APPLICABLE_PROTOCOLS.includes(anchor.protocol);
}
/*
Initialize the page action: set icon and title, then show.
Only operates on tabs whose URL's protocol is applicable.
*/
function initializePageAction(tab) {
if (protocolIsApplicable(tab.url)) {
browser.pageAction.setIcon({tabId: tab.id, path: "../books.png"});
browser.pageAction.setTitle({tabId: tab.id, title: TITLE_APPLY});
browser.pageAction.show(tab.id);
}
}
/*
When first loaded, initialize the page action for all tabs.
*/
var gettingAllTabs = browser.tabs.query({currentWindow: true, active: true});
gettingAllTabs.then((tabs) => {
for (let tab of tabs) {
initializePageAction(tab);
}
});
/*
Each time a tab is updated, reset the page action for that tab.
*/
browser.tabs.onUpdated.addListener((id, changeInfo, tab) => {
initializePageAction(tab);
});
/*
Toggle title when the page action is clicked.
*/
browser.pageAction.onClicked.addListener(toggleT);
I read the documentation again, and a couple other pages. Browser action and page action open the default.html in a new tab so there is no need to use page action on Android. Also the context menu items at the top of my BG script were causing the BG script to not work on Android.
-- Problem Solved.

jCrop resize with correct coords when changing image

Hoping this doesn't get flagged as a duplicate because none of the other q/as on SO have helped me fix this, I think I need a more specific line of help.
I have a profile page on my site that allows the user to change their profile picture without page reloads (via AJAX / jQuery).
This all works fine. The user opens the "Change Profile Picture" modal, selects a file to upload and presses "Crop this image". When this button is pressed, it uploads a file to the website, using the typical way of sending the file and formData (which I append the file data to).
It gets sent backend with the following jQuery:
// Upload the image for cropping (Crop this Image!)
$("#image-upload").click(function(){
// File data
var fileData = $("#image-select").prop("files")[0];
// Set up a form
var formData = new FormData();
// Append the file to the new form for submission
formData.append("file", fileData);
// Send the file to be uploaded
$.ajax({
// Set the params
cache: false,
contentType: false,
processData: false,
// Page & file information
url: "index.php?action=uploadimage",
dataType: "text",
type: "POST",
// The data to send
data: formData,
// On success...
success: function(data){
// If no image was returned
// "not-image" is returned from the PHP script if we return it in case of an error
if(data == "not-image"){
alert("That's not an image, please upload an image file.");
return false;
}
// Else, load the image on to the page so we don't need to reload
$(profileImage).attr("src", data);
// If the API is already set, then we should apply a new image
if(jCropAPI){
jCropAPI.setImage(data + "?" + new Date().getTime());
}
// Initialise jCrop
setJCrop();
//$("#image-profile").show();
$("#send-coords").show();
}
})
});
setJcrop does the following
function setJCrop(){
// Get width / height of the image
var width = profileImage.width();
var height = profileImage.height();
// Var containing the source image
var imgSource = profileImage.attr("src");
// New image object to work on
var image = new Image();
image.src = imgSource;
// The SOURCE (ORIGINAL) width / height
var origWidth = image.width;
var origHeight = image.height;
// Set up the option to jCrop it
$(profileImage).Jcrop({
onSelect: setCoords,
onChange: setCoords,
setSelect: [0, 0, 51, 51],
aspectRatio: 1, // This locks it to a square image, so it fits the site better
boxWidth: width,
boxHeight: height, // Fixes the size permanently so that we can load new images
}, function(){jCropAPI = this});
setOthers(width, height, origWidth, origHeight);
}
And once backend, it does the following:
public function uploadImage($file){
// See if there is already an error
if(0 < $file["file"]["error"]){
return $file["file"]["error"] . " (error)";
}else{
// Set up the image
$image = $file["file"];
$imageSizes = getimagesize($image["tmp_name"]);
// If there are no image sizes, return the not-image error
if(!$imageSizes){
return "not-image";
}
// SIZE LIMIT HERE SOON (TBI)
// Set a name for the image
$username = $_SESSION["user"]->getUsername();
$fileName = "images/profile/$username-profile-original.jpg";
// Move the image which is guaranteed a unique name (unless it is due to overwrite), to the profile pictures folder
move_uploaded_file($image["tmp_name"], $fileName);
// Return the new filename
return $fileName;
}
}
Then, the user selects their area on the image with the selector and pressed "Change Profile Picture" which does the following
// Send the Coords and upload the new image
$("#send-coords").click(function(){
$.ajax({
type: "POST",
url: "index.php?action=uploadprofilepicture",
data: {
coordString: $("#coords").text() + $("#coords2").text(),
imgSrc: $("#image-profile").attr("src")
},
success: function(data){
if(data == "no-word"){
alert("Can not work with this image type, please try with another image");
}else{
// Append a date to make sure it reloads the image without using a cached version
var dateNow = new Date();
var newImageLink = data + "?" + dateNow.getTime();
$("#profile-picture").attr("src", newImageLink);
// Hide the modal
$("#profile-picture-modal").modal("hide");
}
}
});
})
The backend is:
public function uploadProfilePicture($coordString, $imgSrc){
// Target dimensions
$tarWidth = $tarHeight = 150;
// Split the coords in to an array (sent by a string that was created by JS)
$coordsArray = explode(",", $coordString);
//Set them all from the array
$x = $coordsArray[0];
$y = $coordsArray[1];
$width = $coordsArray[2];
$height = $coordsArray[3];
$newWidth = $coordsArray[4];
$newHeight = $coordsArray[5];
$origWidth = $coordsArray[6];
$origHeight = $coordsArray[7];
// Validate the image and decide which image type to create the original resource from
$imgDetails = getimagesize($imgSrc);
$imgMime = $imgDetails["mime"];
switch($imgMime){
case "image/jpeg":
$originalImage = imagecreatefromjpeg($imgSrc);
break;
case "image/png":
$originalImage = imagecreatefrompng($imgSrc);
break;
default:
return "no-work";
}
// Target image resource
$imgTarget = imagecreatetruecolor($tarWidth, $tarHeight);
$img = imagecreatetruecolor($newWidth, $newHeight);
// Resize the original image to work with our coords
imagecopyresampled($img, $originalImage, 0, 0, 0, 0,
$newWidth, $newHeight, $origWidth, $origHeight);
// Now copy the CROPPED image in to the TARGET resource
imagecopyresampled(
$imgTarget, // Target resource
$img, // Target image
0, 0, // X / Y Coords of the target image; this will always be 0, 0 as we do not want any black nothingness
$x, $y, // X / Y Coords (top left) of the target area
$tarWidth,
$tarHeight, // width / height of the target
$width,
$height // Width / height of the source image crop
);
$username = $_SESSION["user"]->getUsername();
$newPath = "images/profile/$username-profile-cropped.jpg";
// Create that shit!
imagejpeg($imgTarget, $newPath);
// Return the path
return $newPath;
}
So basically this the returns the path of the new file, which gets changed to the user's profile picture (same name every time) and uploaded live with a time appended after ? to refresh the image properly (no cache).
This all works fine, however if the user selects another image to upload, after already uploading one, the coords get all messed up (e.g. they go from 50 to 250) and they end up cropping a totally different part of the image, leaving most of it black nothing-ness.
Really sorry for the ridiculous amount of code that is in this question but I'd appreciate any help from people who might have worked around this before.
Some of the code may seem out of place but that's just me trying to debug it.
Thanks, and again, sorry for the size of this question.
-Edit-
My setCoords() and setOthers() functions look like so:
//Set the coords with this method, that is called every time the user makes / changes a selection on the crop panel
function setCoords(c){
$("#coords").text(c.x + "," + c.y + "," + c.w + "," + c.h + ",");
}
//This one adds the other parts to the second div; they will be concatenated in to the POST string
function setOthers(width, height, origWidth, origHeight){
$("#coords2").text(width + "," + height + "," + origWidth + "," + origHeight);
}
I have now resolved this issue.
The problem for me was that when using setJCrop(); - it was not re-loading the image. The reason for this is that the image uploaded and then loaded in to the JCrop window had the same name every time (username as a prefix, and then profile-cropped.jpg).
So to try and resolve this, I used the setImage method which loaded a full-sized image instead.
I got around this by setting the boxWidth / boxHeight params but they just left me with the issue of the coordinates being incorrect every time I loaded a new image in.
Turns out, it was loading the image from the cache every time, even when I was using new Image(); within jQuery.
To solve this, I have now used destroy(); on the jCropAPI and then re-initialised it every time, witout using setImage();
I set a max-width in the CSS on the image itself, which stopped it from being locked to a specific width.
The next problem was that every time I loaded an image a second time, it left the width / height of the old image there, which made the image look all skewed and wrong.
To solve this, I reset the width & height of the image that I use jCrop on, to "" with $(profileImage).css("width", ""); $(profileImage).css("height", ""); before re-setting the source of the image from the new uploaded image.
But I was still left with the issue of using the same name on the images, and then causing it to load from cache every time.
My solution to this was to add an "avatar" column in the database and save the image name in the Database each time. The image was named as $username-$time.jpg and $username-$time.jpg-cropped.jpg where $username is the username of the user (derp) and $time is simply time(); inside PHP.
This meant that every time I uploaded an image, it had a new name, so when any calls were made to this image, there was no cache of it.
Appending like imageName + ".jpg?" + new Date.getTime(); worked for some things but then when sending the image name backend, it didn't work properly, and deciding when to append it / not append it was a pain, and then one thing required it to be appended to force a re-load, but then when appended it didn't work properly, so I had to re-work it.
So the key: (TL;DR)
Don't use the same image name with jCrop, if you are loading a new image; upload an image with a different name and then refer to that one. Cache problems are a pain, and you can't really work around them properly without just using a new name every time, as this ensures that there will be absolutely no more problems (so long as the name is always unique).
Then, when you initialise jCrop, destroy the previous one beforehand if there is one. Use max-width instead of width on an image to stop it from locking the width, and re-set the width / height of the image if you're loading a new one in to the same <img> or <div>
Hope this helps somebody!
I used jcrop and I think this has happened to me. When there is a new image, you have to "reset" jcrop. Try something like this:
function resetJCrop()
{
if (jCropAPI) {
jCropAPI.disable();
jCropAPI.release();
jCropAPI.destroy();
}
}
$("#image-upload").click(function(){
success: function(data){
...
resetJCrop(); // RESETTING HERE
// If the API is already set, then we should apply a new image
if(jCropAPI){
jCropAPI.setImage(data + "?" + new Date().getTime());
}
// Initialise jCrop
setJCrop();
...
}
});
I can't remember the details about why I have to use disable() AND release() AND destroy() in my particular case. May be you can use only one of those. Just try it, and see if that works for you!

Javascript onmouseover trying to add " to text

So I am very new to javascript and web development in general. I am trying to make it so that when you hover over text a small text box pops up with a paragraph in it. The problem is that I need to add " in the text however when I do that the script doesn't work as it recognizes " as part of the code.
I am using nhpup popups to do that nhpopup site
This is what I am trying to add " to
/*
--------------------------------------------------------------------------
Code for link-hover text boxes
By Nicolas Höning
Usage: <a onmouseover="nhpup.popup('popup text' [, {'class': 'myclass', 'width': 300}])">a link</a>
The configuration dict with CSS class and width is optional - default is class .pup and width of 200px.
You can style the popup box via CSS, targeting its ID #pup.
You can escape " in the popup text with ".
Tutorial and support at http://nicolashoening.de?twocents&nr=8
--------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2014 Nicolas Höning
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
nhpup = {
pup: null, // This is the popup box, represented by a div
identifier: "pup", // Name of ID and class of the popup box
minMargin: 15, // Set how much minimal space there should be (in pixels)
// between the popup and everything else (borders, mouse)
default_width: 500, // Will be set to width from css in document.ready
move: false, // Move it around with the mouse? we are only ready for that when the mouse event is set up.
// Besides, having this turned off initially is resource-friendly.
/*
Write message, show popup w/ custom width if necessary,
make sure it disappears on mouseout
*/
popup: function(p_msg, p_config)
{
// do track mouse moves and update position
this.move = true;
// restore defaults
this.pup.removeClass()
.addClass(this.identifier)
.width(this.default_width);
// custom configuration
if (typeof p_config != 'undefined') {
if ('class' in p_config) {
this.pup.addClass(p_config['class']);
}
if ('width' in p_config) {
this.pup.width(p_config['width']);
}
}
// Write content and display
this.pup.html(p_msg).show();
// Make sure popup goes away on mouse out and we stop the constant
// positioning on mouse moves.
// The event obj needs to be gotten from the virtual
// caller, since we use onmouseover='nhpup.popup(p_msg)'
var t = this.getTarget(arguments.callee.caller.arguments[0]);
$jq(t).unbind('mouseout').bind('mouseout',
function(e){
nhpup.pup.hide();
nhpup.move = false;
}
);
},
// set the target element position
setElementPos: function(x, y)
{
// Call nudge to avoid edge overflow. Important tweak: x+10, because if
// the popup is where the mouse is, the hoverOver/hoverOut events flicker
var x_y = this.nudge(x + 10, y);
// remember: the popup is still hidden
this.pup.css('top', x_y[1] + 'px')
.css('left', x_y[0] + 'px');
},
/* Avoid edge overflow */
nudge: function(x,y)
{
var win = $jq(window);
// When the mouse is too far on the right, put window to the left
var xtreme = $jq(document).scrollLeft() + win.width() - this.pup.width() - this.minMargin;
if(x > xtreme) {
x -= this.pup.width() + 2 * this.minMargin;
}
x = this.max(x, 0);
// When the mouse is too far down, move window up
if((y + this.pup.height()) > (win.height() + $jq(document).scrollTop())) {
y -= this.pup.height() + this.minMargin;
}
return [ x, y ];
},
/* custom max */
max: function(a,b)
{
if (a>b) return a;
else return b;
},
/*
Get the target (element) of an event.
Inspired by quirksmode
*/
getTarget: function(e)
{
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
return targ;
},
onTouchDevice: function()
{
var deviceAgent = navigator.userAgent.toLowerCase();
return deviceAgent.match(/(iphone|ipod|ipad|android|blackberry|iemobile|opera m(ob|in)i|vodafone)/) !== null;
},
initialized: false,
initialize : function(){
if (this.initialized) return;
window.$jq = jQuery; // this is safe in WP installations with noConflict mode (which is default)
/* Prepare popup and define the mouseover callback */
jQuery(document).ready(function () {
// create default popup on the page
$jq('body').append('<div id="' + nhpup.identifier + '" class="' + nhpup.identifier + '" style="position:absolute; display:none; z-index:200;"></div>');
nhpup.pup = $jq('#' + nhpup.identifier);
// set dynamic coords when the mouse moves
$jq(document).mousemove(function (e) {
if (!nhpup.onTouchDevice()) { // turn off constant repositioning for touch devices (no use for this anyway)
if (nhpup.move) {
nhpup.setElementPos(e.pageX, e.pageY);
}
}
});
});
this.initialized = true;
}
};
if ('jQuery' in window) nhpup.initialize();
<a onmouseover="nhpup.popup('Action Relating to or affecting the fundamental nature of something; far-reaching or thorough. This is what we offer at Rad Surfing Bali. We provide the most radical way of learning how to surf.');" href='#'>Radical.</a>
Please help me add a " to the text in the html script.
Regards,
Kraz
You should escape '' chars with \.
Like this
<a onmouseover="nhpup.popup('Action Relating to or affecting the fundamental nature of something; far-reaching or thorough. This is what we offer at \'Rad Surfing Bali\'. We provide the most radical way of learning how to surf.');" href='#'>Radical.</a>
Here is working example https://jsfiddle.net/xkj66svc/

Categories

Resources