I am working on a project in which i need to open a new window when a button/link is clicked. and then close it after waiting for a second. Problem is that I want the window to stay open for at least a second. I am able to open and close the window, but the switching is so quick that it defeating the purpose of opening the window in the first place.
I have also looked into setTimeout to create delay, but then again, I believe i m not using it properly. This is how i m doing it right now. Any help will be highly appreciated.
Thanks!!
<html>
<head>
<script type="text/javascript">
function myPopup() {
window.open( "http://arduino.local/arduino/digital/12/1", "myWindow", "status = 1, height = 300, width = 300, resizable = 0" )
window.close();
}
</script>
</head>
<body>
<form>
<input type="button" onClick="myPopup()" value="POP!">
</form>
</body>
</html>
Does this work for you?
function myPopup() {
var myWin = window.open( "http://arduino.local/arduino/digital/12/1", "myWindow", "status = 1, height = 300, width = 300, resizable = 0" )
setTimeout(function() { myWin.close(); }, 2000); // 2 second delay
}
Related
Please help me, I have been working on this for hours. I have just started playing with JavaScript.
So I have a button that loads a new browser window, loads background image. As below, no problems.
HTML
<script>
setBackground();
</script>
JavaScript
function setBackground() {
document.body.style.backgroundColor = "#000000";
document.body.style.backgroundImage = "url(bg.jpg)"
}
Then I try to load another window on button click but the background image will not work. The window works, I can change the background color no problem, but I can't get the image to load. code below.
//load screen on button click
document.getElementById("startButton").onclick = function() {
load()
};
function load() {
//create the new screen
newWindow = window.open("", "", "width=1550, height=800");
newWindow.id = "game";
newWindow.document.body.style.backgroundColor = "#000000";
newWindow.document.body.style.backgroundImage = "url(bg.jpg)";
}
The files and images are located in the same folder, I'm using the same image, it works in the first example but not the second.
Please help!!! Thanks in advance.
Check this link and click on Run
https://www.w3schools.com/code/tryit.asp?filename=GM9IO9Q6SDNL
try this.
<!DOCTYPE html>
<html>
<body onload="setBackground()" >
</body>
<script>
function setBackground() {
document.body.style.backgroundImage = "url(https://www.w3schools.com/html/pic_trulli.jpg)"
newWindowSetBackgroundload()
}
function newWindowSetBackgroundload() {
//create the new screen
var newWindow = window.open("", "", "width=1550, height=800");
//Id use for Uniq thats why its render only one time
// newWindow.id = "game";
//use class for multiple windows genration
newWindow.class = "game";
newWindow.document.body.style.backgroundColor = "#000000";
newWindow.document.body.style.backgroundImage = "url(https://www.w3schools.com/html/pic_trulli.jpg)";
}
</script>
</html>
I have a code that opens a new window with specific height and width. I would prefer, if possible, to open a new tab instead of a new window, but still being able to specify the height and width of the new tab. Is that possible?
<html>
<head>
</head>
<body>
<input type="button" onclick='var myW=window.open
("http://www.google.com/", "mywindow", "width = " + window.screen.width + ", height = " + window.screen.width / 3 + "");'>
</body>
</html>
As I know it is not possible to decide if a new link is opened only in tab. The settings of the browser decide if a new clicked link target="_blank" is opend in a tab or window.
for sure its possible to force with javascript to open a new window and not tab.
Existing Questions:
about forcing open in a new Tab:
HTML: how to force links to open in a new tab, not new window
Resize windows with Javascript:
https://www.w3schools.com/jsref/met_win_resizeto.asp
you can replace myWindow.resizeTo(250, 250); number to change window size
<p>Open a new window, and resize the width and height to 500px:</p>
<button onclick="openWin()">Create window</button>
<button onclick="resizeWin()">Resize window</button>
<script>
var myWindow;
function openWin() {
myWindow = window.open("", "", "width=100, height=100");
}
function resizeWin() {
myWindow.resizeTo(250, 250);
myWindow.focus();
}
</script>
i have a link in my main page that uses ajax to retrieve a PDF which is displayed in an Iframe, i am trying to detect scroll event of the PDF document and display a message or do something. i have tried different solutions from other solutions on stackoverflow and google search in general and couldn't find a good solution.
Main.php
<html>
<!--ajax request-->
<script type="text/javascript">
$(document).on('click','#nextpdf',function(event) {
event.preventDefault();
var reg = $(this).attr("href");
var str = reg.split('?')[1];
$.ajax({
type: "GET",
url: '../functions/pdfreader.php',
data: 'pdfxs='+str+'',
cache:false,
async: false,
success: function(data) {
// data is ur summary
$('.refresh').html(data);
return false;
}
});//end of ajax
});
</script>
<?php
while($obj = $c_content->fetch())
{
$title = $obj['lecture_title'];
echo '<article class="comment2">
//pdf link
<div class="comment2-body">
<div class="text" style="color:#999;padding-right:130px;">
<p><a href="../functions/pdfreader.php?'.$title.'""
style="color:#999" id="nextpdf">'.$title.'</a></p>
</div>
</div>
</article>
';
}
?>
</html>
pdfreader.php
//detect iframe pdf scroll
<script type="text/javascript">
$("myiframe").load(function () {
var iframe = $("myiframe").contents();
$(iframe).scroll(function () {
alert('scrolling...');
});
});
</script>
<?php
........
while($obj = $gettrend->fetch())
{
$coursefile = $obj['lecture_content'];
//this is my iframe
echo '<div class="mov_pdf_frame"><iframe id="myiframe"
src="https://localhost/einstower/e-learn/courses/pdf/'.$coursefile.'"
id="pdf_content"
width="700px" height="800px" type="application/pdf">
</iframe></div>';
}
?>
The major problem here is that nothing happens when i scroll the pdf document, how can i detect scrolling?
i found this fiddle that works but i cant view the javascript solution. http://fiddle.jshell.net/czw8pbvj/1/
First off, $("myiframe") isn't finding anything, so it attaches a load event to nothing. 1) change it to $("#myiframe") or $("iframe").
Here's a working fiddle (for iframe scroll detection)
UPDATE: to detect the scroll within PDF document, you can't use iframe. For that, you need embed or object tags AND a JS-enabled PDF document (hopefully its your PDFs..), who can send messages to your page's JS (see this answer).
Unfortunately, I couldn't find a scroll event in Adobe's Acrobat API Reference. It lists only these events:
Event type: Event names
App: Init
Batch: Exec
Bookmark: Mouse Up
Console: Exec
Doc: DidPrint, DidSave, Open, WillClose, WillPrint, WillSave
External: Exec
Field: Blur, Calculate, Focus, Format, Keystroke, Mouse Down, Mouse Enter, Mouse Exit, Mouse Up, Validate
Link: Mouse Up
Menu: Exec
Page: Open, Close
Screen: InView, OutView, Open, Close, Focus, Blur, Mouse Up, Mouse Down, Mouse Enter, Mouse Exit
So, basically, I think what you want just isn't possible as for now, at least with default rendering. With custom rendering (https://github.com/mozilla/pdf.js) it could be possible, though I'm not sure.
Apparently, it could be done with page scroll (see this issue). So back to iframes solution. :^D
Because this question is asked a long time ago, i think i need to help with my experience before.
The answer is: You can not
Why? because PDF is rendered by external apps, such as adobe pdf reader, foxit or else. And you can not attach event on them.
if you are using adobe reader, The only you can do is goto page, change zoom etc. Full example you can read here: https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf#page=8 (see. i bring you to page 8 directly instead to first page).
But, hei.. how if our client using another apps? we will confused more
The way to do this is only build your own pdf viewer.
we can using js library, like: http://www.bestjquery.com/2012/09/best-jquery-pdf-viewer-plugin-examples/
but here i only will show you to use pdf.js which created by mozilla.
main.php
<style>
.preview{
display:none;
width: 400px;
height: 400px;
border: 1px solid black;
}
</style>
file/test.pdf<br>
file/test1.pdf<br>
<div class="preview">
<iframe id="myiframe" frameborder="0" width="400px" height="400px" >not support iframe</iframe>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$(document).on('click', '#nextpdf', function(e){
e.preventDefault();
$('#myiframe').attr('src', $(this).attr('href'));
$('.preview').show();
});
//handle iframe on scroll
$('#myiframe').on('load', function () {
$(this).contents().scroll(function () {
console.log('scrolled');
}).click(function(){
console.log('clicked');
});
});
});
</script>
pdfreader.php
<?php
$path = 'file/';
$pdf = isset($_GET['pdfxs']) ? $path . $_GET['pdfxs'] : '';
if(!file_exists($pdf) || !mime_content_type($pdf) =='application/pdf') die('file not found');
?>
<div id="pdf-container">
<div id="pdf-box"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>
<script>
$(function(){
//original script : https://gist.github.com/fcingolani/3300351
function renderPDF(url, canvasContainer, options) {
var options = options || { scale: 1 };
function renderPage(page) {
var viewport = page.getViewport(options.scale);
var canvas = $(document.createElement('canvas'));
var renderContext = {
canvasContext: canvas[0].getContext('2d'),
viewport: viewport
};
canvas.attr('width', viewport.width).attr('height', viewport.height);
canvasContainer.append(canvas);
page.render(renderContext);
}
function renderPages(pdfDoc) {
for(var num = 1; num <= pdfDoc.numPages; num++)
pdfDoc.getPage(num).then(renderPage);
}
PDFJS.disableWorker = true;
PDFJS.getDocument(url).then(renderPages);
}
renderPDF('<?=$pdf;?>', $('#pdf-box'));
});
</script>
Note: i put pdf on folder file/
in main.php you will notice that you can attach event scroll (and click too) to the pdf. because our pdf is not rendered by external apps now.
and the last part is, if you read pdfreader.php carefully, you will notice that you no need iframe anymore. You just need div, and then you can fully handle all event that do you want to your pdf : like scroll, click, change page, zoom, etc. why?? because your pdf is redered as canvas now (pdf.js render your pdf as HTML5 canvas). see full example of pdf.js
Please try this
iframe.on( "scroll", handler )
$("#frame").scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height())
alert('Bottom reached');
});
I found this in the JSFiddle that was referenced in the Fiddle you linked. The HTML field is empty. This CSS was in there, too.
body {
height: 1500px;
}
In the fiddle that you linked, the <iframe> has an ID of frame. I figured you can use the jQuery selector like $("#frame").
I think this will help you.
$("#myiframe").load(function () {
$(this).contents().scroll(function () {
//your code here
});
});
i want to make my pop up window will showing behind main windows.
say it window 1 is main windows and window 2 is popup window.
so when someone click window 1, window 2 will pop up behind window 1.
im already try window.focus and window.blur but no one working. remember this, I'm just making this one for learning.
<script type="text/javascript">
var popup = function() {
var lastShownTs = +localStorage.getItem("lastShown");
var currentDate = new Date();
currentDate.setHours(0, 0, 0, 0);
var lastShown = null;
if (!isNaN(lastShownTs)) {
lastShown = new Date(lastShownTs);
lastShown.setHours(0, 0, 0, 0);
}
if (lastShown == null || lastShown.getTime() != currentDate.getTime()) {
window.open("example.com", "Window", "status=1,toolbar=1,width=1,height=1,left=5000,top=5000,scrollbars=1,resizable=1");
localStorage.setItem("lastShown", currentDate.getTime());
}
window.focus();
popup.blur();
}
</script>
<body onclick="popup()"></body>
I believe what you are looking for is referred to as a "Pop-under".
See https://developer.mozilla.org/en-US/docs/Web/API/Window/open.
Alternately, here is a cheat using tabs ...
<script>
function popunder() {
var currentURL = document.URL;
window.open(currentURL, '_blank', 'toolbar=yes, location=yes, status=yes, menubar=yes, scrollbars=yes');
window.location = 'http://www.stackoverflow.com';
}
</script>
Click here!
Tested Chrome 62.0.3202.62.
I am trying to open a location in new window(tab) using window.open. It is not working in chrome. First I tried with window.open(url,name), this did not work, however this works in every other browser. Then I used something like this,
var w = window.open("about:blank");
w.opener = null;
w.document.location = url;
This opens the url in same tab but not in separate tab.
Are you sure your popup is not being blocked? Most popup windows that didn't happen in response to a user event will get blocked. I typed window.open("google.com", "_blank") into the console and I got the blocked window on the url bar
Do it like this
window.open( url, "_blank" );
Remember, the 2nd parameter is analogous to an anchor tag's target attribute.
Try this. Works in IE8, fails in FF when popups are blocked
<html>
<head>
<script type="text/javascript">
if(typeof HTMLElement!='undefined'&&!HTMLElement.prototype.click)
HTMLElement.prototype.click=function(){ // event by Jason Karl Davis
var evt = this.ownerDocument.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
}
function loadAndClick(url,target) {
var lnk = document.createElement("a");
lnk.href=url;
lnk.target=target||"_blank"
lnk.id="myLink"
lnk.onclick=function() {
var w = window.open(this.href,this.target);
return (w)?false:true;
}
document.body.appendChild(lnk);
document.getElementById('myLink').click();
// lnk.click();
}
window.onload=function() { // or call getURL("javascript:loadAndClick('http://www.google.com')");
loadAndClick("http://www.google.com");
}
</script>
</head>
<body>
</body>
</html>
Create a redirect page (for example Redirect.aspx).
window.open('Redirect.aspx?URL=http://www.google.com', '_blank');
From the Redirect.aspx page, redirect to the URL specified in the QS...
This worked a treat for me with Chrome blocking my new windows.