Getting broken image but it loads as a new tab - javascript

I have the following little script that seems to work but two of the images appear broken. They load when I right click and load as new tab:
var target = document.getElementById('target');
var counter = 0;
var myPictures = [
'https://media.giphy.com/media/3ohhwJax6g4Y8BK30k/giphy.gif',
'https://media.giphy.com/media/3o7aD5tv1ogNBtDhDi/giphy.gif',
'https://media.giphy.com/media/1nkUav308CBws/giphy.gif'
];
function nextPic() {
counter += 1;
if (counter > myPictures.length -1) {
counter = 0;
}
target.src = myPictures[counter];
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img id="target" src="https://media.giphy.com/media/1nkUav308CBws/giphy.gif" width="107" height="98" />
<input type="button" onclick="nextPic()" value="change image" />
</body>
</html>

Just move this line inside your nextPic() function so you don't try to grab that div before it gets loaded in the DOM.
function nextPic() {
var target = document.getElementById('target');
...
Sometimes <script defer> will automagically wait for the DOM to load, sometimes it doesn't. It's JavaScript. It is what it is.
defer
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded. This attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect. To achieve a similar effect for dynamically inserted scripts use async=false instead.
Here's a good backstory on script loading.

var target = document.getElementById('target');
var counter = 0;
var myPictures = [
'https://media.giphy.com/media/3ohhwJax6g4Y8BK30k/giphy.gif',
'https://media.giphy.com/media/3o7aD5tv1ogNBtDhDi/giphy.gif',
'https://media.giphy.com/media/1nkUav308CBws/giphy.gif'
];
function nextPic() {
counter += 1;
if (counter == myPictures.length -1) {
counter = 0;
}
target.src = myPictures[counter];
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img id="target" src="https://media.giphy.com/media/1nkUav308CBws/giphy.gif" width="107" height="98" />
<input type="button" onclick="nextPic()" value="change image" />
</body>
</html>

Related

Why can I write to sessionStorage from an iframe on the first try, but not any consecutive tries? (Chrome Version 74)

This issue has shown up in the latest version of Chrome (74.0.3729.108). This is unique to the local filesystem, as I have other ways of loading up neighboring documents in iframes when the app is on a server.
In my app, we have been able to load up documents from the filesystem with JavaScript by writing iframes to the DOM, and then having the document in the iframe write it's innerHTML to sessionStorage. Once the iframe is done loading, we catch that with the onload attribute on the iframe and handle getting the item written to sessionStorage.
I have narrowed this down to some bare-bones code and found that this works only on the first try, and then any tries after the first fail.
Here is a minimal HTML document:
<!DOCTYPE html>
<html>
<head>
<title>Chrome iFrame Tester</title>
<script src="iframe-load.js"></script>
</head>
<body onload="OnLoad()">
<div id="result"></div>
</body>
</html>
Here is the JavaScript:
var urls = ['file://C:/Users/afrench/Documents/Other/Misc%20Code/Chrome%20iFrame/Doc1.html',
'file://C:/Users/afrench/Documents/Other/Misc%20Code/Chrome%20iFrame/Doc2.html'];
HandleLoad = function () {
'use strict';
var data;
try {
data = window.sessionStorage['data'];
delete window.sessionStorage['data'];
} catch (ignore) {
// something went wrong
}
var container = document.getElementById('container');
window.document.body.removeChild(container);
if (data !== null && data !== undefined) {
var resultContainer = document.getElementById('result');
resultContainer.innerHTML += data;
}
if (urls.length > 0) {
OnLoad();
}
}
function OnLoad() {
var url = urls[0];
if (url) {
urls.splice(0, 1);
var container = document.createElement('div');
container.id = 'container';
container.style.visibility = 'hidden';
window.document.body.appendChild(container);
container.innerHTML = '<iframe src="' + url + '" onload="HandleLoad();"></iframe>';
}
}
In the filesystem, we have the HTML written into index.html, and right next to it are two minimal HTML files, Doc1.html and Doc2.html. Their contents are both identical except the identifying sentence in the body's div:
Neighbor document HTML:
<!DOCTYPE html>
<html>
<head>
<title>Chrome iFrame Tester</title>
<script>
function OnLoad() {
try {
window.sessionStorage['data'] = window.document.body.innerHTML;
} catch {
// no luck
}
}
</script>
</head>
<body onload="OnLoad()">
<div>This is Doc 1's content!</div>
</body>
</html>
When this is run, we should see the content HTML of the two neighbor documents written to the result div in index.html.
When I run this minimal example, I can see that the content is successfully written to sessionStorage and then to the DOM for the first document, but the next try fails. What can I do to get it to work consistently, and what is happening here that it fails?
I'm not sure what is causing the weird behavior, so hopefully someone else can provide some insight on what exactly is going on here.
In the meantime, here is an alternative solution using window.postMessage:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Chrome iFrame Tester</title>
<script src="iframe-load.js"></script>
</head>
<body onload="OnLoad()">
<div id="result"></div>
</body>
</html>
iframe-load.js
var urls = ['file://C:/Users/afrench/Documents/Other/Misc%20Code/Chrome%20iFrame/Doc1.html',
'file://C:/Users/afrench/Documents/Other/Misc%20Code/Chrome%20iFrame/Doc2.html'];
window.addEventListener('message', event => {
'use strict';
var data = event.data;
var container = document.getElementById('container');
window.document.body.removeChild(container);
if (data) {
var resultContainer = document.getElementById('result');
resultContainer.innerHTML += data;
}
if (urls.length > 0) {
OnLoad();
}
})
function OnLoad() {
var url = urls.shift();
if (url) {
var container = document.createElement('div');
container.id = 'container';
container.style.visibility = 'hidden';
window.document.body.appendChild(container);
container.innerHTML = '<iframe src="' + url + '"></iframe>';
}
}
Doc1.html
<!DOCTYPE html>
<html>
<head>
<title>Chrome iFrame Tester</title>
<script>
function OnLoad() {
window.parent.postMessage(window.document.body.innerHTML, '*');
}
</script>
</head>
<body onload="OnLoad()">
<div>This is Doc 1's content!</div>
</body>
</html>

Pass jquery variable to iframe src

I want to pass the value which i get from a text box to the src of my iframe. I am using the following code to get the value from textbox, on the button click it should be passed to the iframe src and replace the query:'*' with the variable passed, i.e. the * should be replaced.
How to proceed with this?
Foloowing is the iframe with html code
<iframe src="http://localhost:5601/#/dashboard/New-Dashboard?embed&_a
=(filters:!(),panels:!((col:1,id:env,row:1,size_x:4,size_y:3,type:visualization)
,(col:5,id:env-2,row:1,size_x:4,size_y:3,type:visualization),(col:9,id:env-3,
row:1,size_x:4,size_y:3,type:visualization)),query:(query_string:(analyze_wildcard:
!t,query:'*')),title:'New%20Dashboard')&_g=(refreshInterval:(display:Off,pause
:!f,section:0,value:0),time:(from:now%2Fy,mode:quick,to:now%2Fy))" height="600"
width="800" id="myframe"></iframe>
<!DOCTYPE html>
<html>
<head>
<title>jQuery With Example</title>
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('.btnGetName').click(function (event) {
var name = $('.txtName').val();
alert(name);
});
});
</script>
</head>
<body>
<div>
<input type="text" class="txtName" value="hello" id="querypass"/><br />
<button class="btnGetName">Get Name</button>
</div>
</body>
</html>
Try this
var src = $('#myframe').attr('src');
var newSrc = src.replace("query:'*'", "query:'" + name + "'");
$('#myframe').attr('src', newSrc);
You can try following code:
Note: Assuming that your <iframe> is within same HTML document:
$('.btnGetName').click(function (event) {
var name = $('.txtName').val();
alert(name);
var iframeObj = $("#myframe");
var srcString = iframeObj.attr("src");
srcString = srcString.replace("query:'*'","query:'"+name+"'");
iframeObj.attr("src",srcString );
});
Please make sure that you don't put single quote in your text field.

Onclick is not working when use that as object

This is works fine when i am using addEventListener. But, it is not working when i use button.click . what is the mistake on the below code? what is the cause it is not working on varNext.click= myFunc;?
[code]
<!doctype html>
<html>
<head>
<title>Slideshow</title>
<script type="text/javascript">
var images = ['home_default.png','about_default.png','blog_default.png','logo.png'];
function myFunc(){
var var1 = document.getElementById("slideimage");
var var2 = var1.name.split("_");
//alert(var2);
index = var2[1];
if(index == images.length - 1){
index = 0;
}else {index++;}
var1.name = "image_" + index;
var1.src = images[index];
}
</script>
</head>
<body>
<p><img id="slideimage" name="image_0" src="home_default.png" alt="Home"></p>
<form name="slideform">
<input type="button" id="nextbtn" value="Next">
</form>
<script type="text/javascript">
var varNext = document.getElementById("nextbtn");
//varNext.addEventListener("click", myFunc, false);
varNext.click= myFunc;
</script>
</body>
</html>
[/code]
Rather than .clickfires the element's click event it must be .onclickproperty returns the onClick event handler
Try this
varNext.onclick = myFunc;
Demo Fiddle of your code
You need to use the onclick attribute
varNext.onclick = myFunc;

Maintain div scroll position on postback with html/javascript

Is there a way to maintain the div scroll position on a postback, without using asp? So far I've only found solutions using asp.
http://blogs.x2line.com/al/articles/156.aspx
<!doctype html>
<html>
<head>
<title></title>
<script language="javascript">
// function saves scroll position
function fScroll(val)
{
var hidScroll = document.getElementById('hidScroll');
hidScroll.value = val.scrollTop;
}
// function moves scroll position to saved value
function fScrollMove(what)
{
var hidScroll = document.getElementById('hidScroll');
document.getElementById(what).scrollTop = hidScroll.value;
}
</script>
</head>
<body onload="fScrollMove('div_scroll');" onunload="document.forms(0).submit()";>
<form>
<input type="text" id="hidScroll" name="a"><br>
<div id="div_scroll" onscroll="fScroll(this);" style="overflow:auto;height:100px;width:100px;">
.. VERY LONG TEXT GOES HERE
</div>
</form>
</body>
</html>
Maybe this javascript code works for you
function loadScroll ()
{
var m = /[&?]qs\=(\d+)/.exec (document.location);
if (m != null)
myDiv.scrollTop = parseInt (m[1]);
}
function saveScroll ()
{
var form = document.getElementById ("myForm");
var sep = (form.action.indexOf ("?") == -1) ? "?" : "&";
form.action += sep + "qs=" + myDiv.scrollTop;
}
Now, you can watch for the "submit" event to save the position in the "action" attribute:
document.getElementById ("myForm").addEventListener ("submit", saveScroll, false);
And in your BODY tag...
<body onload="loadScroll ();">
....
</body>
I can't test the code right now, but I think you get the idea.

Javascript delayed image loading

I am trying to delay the loading of images using plain JS. my method to do this is by giving empty src field for the image and inserting the image url into a temp attribute called "lang" as used in the example below. ie >
<img lang="logo.gif"> instead <img src="logo.gif">. When pressing a button the js below is initiated to insert into src attr the value of the dummy "lang" attr.
function showimagesunderdiv(divid)
{
tr = document.getElementById(divid);
pics=tr.getElementsByTagName('img');
for(i=0;i<pics.length;i++)
{
if(pics[i].lang)
{
pics[i].src=pics[i].lang;
pics[i].style.display='';
}
}
}
While this works is Chrome and FF, IE is doing problems. Any idea?
Maybe this:
<html>
<body>
<p>Images:</p>
<img name=image0>
<img name=image1>
<img name=image2>
<img name=image3>
End of document body.
</body>
<script type="text/javascript">
function LoadImage(imageName,imageFile)
{
if (!document.images) return;
document.images[imageName].src = imageFile';
}
LoadImage('image4','number4.gif');
LoadImage('image5','number5.gif');
LoadImage('image6','number6.gif');
LoadImage('image7','number7.gif');
</script>
</html>
Or this:
<html>
<body>
<p>Images:</p>
<img name=image0 onLoad="LoadImage('image1','number1.gif')">
<img name=image1 onLoad="LoadImage('image2','number2.gif')">
<img name=image2 onLoad="LoadImage('image3','number3.gif')">
<img name=image3>
End of document body.
</body>
<script type="text/javascript">
var loadingImage = false;
function LoadImage(imageName,imageFile)
{
if ((!document.images) || loadingImage) return;
loadingImage = true;
if (document.images[imageName].src.indexOf(imageFile)<0)
{
document.images[imageName].src = imageFile;
}
loadingImage = false;
}
LoadImage('image0','number0.gif');
</script>
</html>
I know it is not a correction of your code but I cant see whats wrong...
This is a very compatible solution!
Hope it helps! resource:
http://www.cryer.co.uk/resources/javascript/script3.htm
Give each image tag an ID, store the IDs and URLs in an array:
imagesToLoad = [["imgId1", "http://..."], ["imgId2", "..."], ...];
And use:
function showimages(imageList)
{
for(var x = 0; x < imageList.length; x++) {
document.getElementById(imageList[x][0]).src = imageList[x][1];
}
}
showImages(imagesToLoad);

Categories

Resources