OnClick Functions Only Work On Second Click - javascript

I have the following code that creates a few functions: hidePara1(), which toggles between the CSS hidden attribute of a paragraph; and displayFrame(), which does the same with the display attribute of an Iframe. Both the paragraph and the Iframe are set to display:none and visibility:hidden respectively, using CSS.
var Par1 = document.getElementById("para1");
var Frame1 = document.getElementById("iframe1");
function hidePara1() {
Par1.style.display = ((Par1.style.display!='none') ? 'none' : 'block')
}
function displayFrame() {
Frame1.style.visibility = ((Frame1.style.visibility!='hidden') ? 'hidden' : 'visible');
}
And the HTML where the elements exist, and in which I also call the functions via onClick attributes.
Display iFrame
<div class="frame-container"><iframe id="iframe1" src="somelink" width="800" height="460"></iframe></div>
<img id="img1" onClick="hidePara1();" src="someimage.jpg">
<div id="para1">
<p>This is the text for paragraph 1.</p>
</div>
The problem is bizarre: both onclick events work perfectly, from the second click onwards. In other words, neither works when first clicked. This seems to be quite a common problem, judging by the tons of other similar questions I came across, but I can't figure it out, and one of those questions could help me. Note that it also needs to be vanilla JS - frameworks won't do.
A solution to this would be very appreciated.
Thanks

In the handler, you access Par1.style. The style property of an element refers to the style properties in an inline style="..." HTML attribute. You specified that elsewhere, you had something like the following in CSS:
#para1 {
display: none;
}
This doesn't get picked up in Par1.style.display. Look into getComputedStyle if you want to see what's currently applied. fiddle
Or just do your conditional the other way around:
Par1.style.display = ((Par1.style.display!='block') ? 'block' : 'none')

When you say that these elements are styled using CSS, I assume you mean "styled using some selector, e.g. #para1 { display:none; }".
Par1.style.display however, only looks for the style attribute on your div, which - in the case assumed above - is initially not set. Therefore, the first click will set style="display:none;" on the div, which you should be able to observe using developer tools or firebug.

FIDDLE DEMO
Your code works perfectly on the fiddle.
Display iFrame
<div class="frame-container"><iframe id="iframe1" src="somelink" width="800" height="460"></iframe></div>
<img id="img1" onclick="hidePara1();" src="someimage.jpg">
<div id="para1">
<p>This is the text for paragraph 1.</p>
</div>
<script>
var Par1 = document.getElementById("para1");
var Frame1 = document.getElementById("iframe1");
function hidePara1() {
Par1.style.display = ((Par1.style.display!='none') ? 'none' : 'block')
}
function displayFrame() {
Frame1.style.visibility = ((Frame1.style.visibility!='hidden') ? 'hidden' : 'visible');
}
</script>

these:
var Par1 = document.getElementById("para1");
var Frame1 = document.getElementById("iframe1");
shoud be done on load, i.e.:
// Global declaration, thos I don't think this matter as much as....
var Par1 ;
var Frame1 ;
// ...this. Your calls to getElementById() may be executing before
// the page has finished loading. Making the assignment in OnLoad
// guarantees the elements are available an I'm thinking should fix
// the issue with it not working first time through.
function init() {
Par1 = document.getElementById("para1");
Frame1 = document.getElementById("iframe1");
}
html:
<body onload="init();">

Related

Iframe nomenucontext - Modify img tag after creation

Hi I am adding a iframe dynamically, It displays an image from a server. I need to disable the context menu for this item. In chrome I can inspect element and if I add oncontextmenu="return false" I do get the wanted affect. However I am unable to do this while the page is generated. Here is an example of the working html.
However I can not reproduce this when i frame is being created. Here is my code.
$(window).scrollTop(0);
$('#secVerify').show();
$("#popWaitLoad").modal("hide");
imgLoading.hide();
dvIframe.empty();
//else load deposit data into interface
$("#spanType").text(deposit.DepositType);
$("#spanReference").text(deposit.Reference);
$("#spanAmount").text("R " + deposit.Amount.toFixed(2));
$("#spanDate").text(deposit.DateCreatedOffsetS);
imageID = deposit.Deposit_Doc_imageID;
var url = imageUrl + '/' + deposit.Deposit_Doc_imageID + '/false';
var imgFrame = document.createElement("iframe");
imgFrame.src = url;
imgFrame.frameBorder = '0';
imgFrame.scrolling = 'no';
imgFrame.width = '100%';
imgFrame.height = '100%';
imgFrame.align = 'middle';
imgFrame.id = "iframeImg";
dvIframe.append(imgFrame);
I have tried examples like.
$("#iframeImage").contents().find("img").attr("oncontextmenu", 'return false');
$('#iframeImage img').on('contextmenu', function (e) {
e.stopPropagation();
// Your code.
return false;
});
But because the img element seems to be only created is done after page load it seems to not work. I know disabling the the menu will not help much and I have explained all the other methods of obtaining the image that is still available but the client really wants this.
I have added nocontextmenu to the body tag and it works everywhere except for the iframe.
So let me clarify, My iframe is working like it should however I would like to disable the right click aka context menu on the specific iframe.
I have used setAttribute to set the attributes and targeted a container to appendChild.
function example(){
var target = document.getElementById('container');
var element = document.createElement('img');
element.setAttribute('src', 'http://gopalshenoy.files.wordpress.com/2011/04/product_demos.jpg');
//element.setAttribute('width','100%');
//element.setAttribute('height','100%');
element.setAttribute('id','iframeImage');
element.setAttribute("oncontextmenu","return false;");
target.appendChild(element);
}
// Demo-Snippet use.
window.onload=example;
<!-- Demo Snippet use -->
<div id="container"></div>
If you build more than one element using this function you might find further issues due to duplicated ID's.
ID's are used to target a specific element 'one of' so if you want to build multiple elements I would recommend giving them unique ID's.
I hope this helps. Happy coding!

How to store iframe in a variable?

<html>
<body>
<iframe id="src">
</body>
</html>
I want to have the iframe show up in the div element through a Javascript function but I can't seem to figure out what isn't working. Any ideas?
document.getElementById('site').src = http://www.w3schools.com/;
Thanks in advance!
Try
document.getElementById('src').src = 'http://www.w3schools.com/';
a) the url should be provided as string (quoted)
b) the id of your iframe is src not site
Your iframe don't have the id site, so your code won't have any effect.
(Also please note that you didn't close the iframe tag) .
Here's the right code (fiddle) .
<input type="button" onclick="changeIframeSrc('myFrame');" value="changeSrc">
<iframe src="http://www.example.com" id="myFrame"></iframe>
<script>
function changeIframeSrc(id) {
e = document.getElementById(id);
e.src = "http://www.wikipedia.com/";
}
</script>
First, a couple small things:
the id on your iframe appears to be src and not site; and
you need to close the iframe tag.
Assuming that you're just dealing with one iframe and it has an id then by all means:
var myIframe = document.getElementById('src');
// gives you just that one iframe element
You may want to consider document.querySelectorAll though, in case you're working with more than one iframe.
var iframes = document.querySelectorAll('iframe');
See that in action: http://jsbin.com/equzey/2/edit
And important side note: if all you need is access to the iframe element (e.g., to manipulate its source or to apply CSS via the style attribute) then the above should be fine. However, if you need to work with the contents of the iframe, you'll need to get inside its web page context with the contentWindow property:
var iframes = document.querySelectorAll('iframe');
iframes[0].contentWindow;

Hiding a div through javascript

My question is I have a div and I want to make it invisible through a javascript function, easy as that, seems like something a lot of people would have done, and I've researched it pretty thoroughly, however it doesn't seem to work. Here is my code (greatly simplified to just show the problem) Forgive the poor HTML formatting, I did that to keep the website from thinking I was trying to post a link.
function HideDiv()
{
var elem = Document.getElementById('divID');
elem.style.display = "none";
elem.style.visibility = "hidden";
}
function buttonFunction()
{
var elem = Document.getElementById('buttonID');
elem.src="a new url";
}
<div id="divID" style="background: url('a url') top center no-repeat " >
<center>
<anchor onclick="buttonFunction" (a hyper reference here)="#">
<img src="a url" vspace ="35" border = "0" id="buttonID">
</anchor>
</center>
</div>
Does having those anchors in the div prevent the hiding functionality? The reason I have both display and visibility on the div is that my understanding is that those functions work differently between firefox and IE, so I included both as a way to make sure that regardless of browser this will work. I have tried using either function individually in FF IE and Chrome to no result, the Div remains visible. Additionally, I'd like the anchors to become invisible as well if at all possible.
Thanks,
Tom
Document should be document.
I'm also not sure if having <anchor> instead of <a> was part of your attempt to "keep the website from thinking I was trying to post a link". (See David's answer below for how the entire <a> should be written.)
It may not be shown here, but I can't see where HideDiv() is called from.
<a onclick="buttonFunction(); return false;" href="#">
<img src="url" vspace ="35" border = "0" id="buttonID" />
</a>
jQuery makes this easy.
$("#divId").hide();
(haven't tried this, but I'm sure it's close to the correct syntax)

Image visibility one

I have a few images with: visibility:hidden and an onClick event which sets its visibility to visible. Images have an id of Img_(somenumber)
How can I make so that when one image is visible all others should be hidden?
Using jquery you could try the following:
Add a class to the set of images you want to manipulate their visibility. e.g.
Then for each image you could to the following for the onclick event:
<img src="{img_src}" class="myImages" onclick="$('img.myImages').hide(); $(this).show();" />
The above, of course, requires that you change each image tag.
If you cannot do that (large number of images), then try using a function that will be triggered when the document loads and will add a handler for the 'onclick' event of each image. Again this easy easily achieved using jquery or another js library.
There are a ton of ways to do this. I'm pretty sure you will want to think through it more. BUT, For an answer without jQuery. Add this as your onClick handler. Make sure you pass the this keyword.
<img onclick="toggleVisible(this);" src="" />
Include this function in your page somewhere:
function toggleVisible(clickedLI) {
var imgs = document.getElementsByTagName('img');
var i = imgs.length;
while (i--) {
var img = imgs[i];
if (img.id.indexOf('Img_' == 0)) {
img.style.visibility = img.parentNode == clickedLI ? 'visible' : 'hidden';
}
}
}
The first problem you will run into is that there is no way to bring back the hidden images. They are there, taking up space in the document, but they won't respond to the click events (at least not in Chrome.) Consider giving more detail in your question. As andreas said, if you have a lot of images there are more efficient ways.

Javascript problem with iframe that's hidden before loaded

I have a page that contains an iframe that gets loaded using Javascript:
index.html
<iframe id="myFrame" width="800" height="600" style="display: none;"></iframe>
<div id="loader"><!-- some loading indicator --></div>
<script type="text/javascript">
function someFunction() {
var myFrame = document.getElementById('myFrame');
var loader = document.getElementById('loader');
loader.style.display = 'block';
myFrame.src = 'myFrame.html';
myFrame.onload = function() {
myFrame.style.display = 'block';
loader.style.display = 'none';
};
}
</script>
The page that gets loaded in the iframe contains some Javascript logic which calculates the sizes of certain elements for the purposes of adding a JS driven scrollbar (jScrollPane + jQuery Dimensions).
myFrame.html
<div id="scrollingElement" style="overflow: auto;">
<div id="several"></div>
<div id="child"></div>
<div id="elements"></div>
</div>
<script type="text/javascript">
$(document).load(function() {
$('#scrollingElement').jScrollPane();
});
</script>
This works in Chrome (and probably other Webkit browsers), but fails in Firefox and IE because at the time jScrollPane gets called, all the elements are still invisble and jQuery Dimensions is unable to determine any element's dimensions.
Is there a way to make sure my iframe is visible before $(document).ready(...) gets called? Other than using setTimeout to delay jScrollPane, which is something I definitely want to avoid.
Some browsers assume that when "display:none" is applied to replaced elements (like Flash or an iframe) the visual info for that element is no longer needed. So, if the element is later displayed by the CSS, the browser will actually recreate the visual data form scratch.
I imagine that having the iframe default to "display:none;" makes the browser skip the rendering of the HTML so the tags don't have any dimensions. I would set the visibility to "hidden" or position it off the page rather than use "display:none;".
Good luck.
instead of making the iframe invisible by using display:none, you could try to...
... set visibility:hidden
... set position:absolute; top:-600px;
... set opacity:0
or something else that makes jQuery "see" the objects but not the user (and reset the used css-attributes in your myFrame.onload function).
visibility:collapse;
display:hidden;
height:0px;
Will work to get rid of white space too..
The iframe will also load..
Hidden iframes are a huge security issue. Probably best to try to find another way to accomplish what you want, if it is legitimate, because hopefully future browsers will get rid of this feature altogether. http://blog.opendns.com/2012/07/10/opendns-security-team-blackhole-exploit/

Categories

Resources