I've gone through lot of topics related to this question but unable to get the desired output.
I'm calling a iframe inside and html like this:
<iframe class="full-screen-preview__frame" id="nitseditpreview" src="himu/index.php" name="preview-frame" frameborder="0" noresize="noresize" data-view="fullScreenPreview">
Suppose in this iframe I have h2 tag with a class name like this:
<body>
<section id="about-us">
<div class="container">
<div class="text-center">
<div class="col-sm-8">
<h2 class="maincontent">
Why with Us
</h2>
</div>
</div>
</div>
</section>
</body>
As seen by the inspect element in browser
By using Jquery I want to manipulate this lets say for example I want to put border in this. I've tried a lot of things but I guess this thing will work if anyone fixes the bug, my jquery looks like this:
$(document).load(function () {
$('#nitseditpreview').load(function () { //The function below executes once the iframe has finished loading
$this = $(this);
$('#nitsmenu', this.contents()).css('border', 'solid 1px #777');
});
});
Don't know where I'm doing mistake, even I'm following same origin policy too.
If both framed and framing documents are on the same domain, there shouldn't be any need for sandbox attributes or CORS hoop-jumping. But there are a number of other errors here:
$(document).load(...) should be $(document).ready(...) (since it has already loaded by the time your script runs)
you define $this = $(this), but then in the next line try to use a bare this
You're trying to match a #nitsmenu that doesn't appear to exist in the framed document
The following appears to work, although I'm concerned there may still be a race condition on that iframe's .load():
$(document).ready(function() {
$('#nitseditpreview').load(function() {
$(this).contents().find('.container').css('border', 'solid 1px #777');
});
});
http://plnkr.co/edit/tCEHdU0ckg5q4w4tPVFU
Related
I need to create a tightly controlled environment for opening certain pages that need back and forward navigation controls. I had poked around on here and found this question and tried to implement it, but I'm having a problem.
I have the following for the HTML and Javascript going on, assume it's already styled (reusing code from previous project), and JQuery is already listed in the <head></head> tags:
<body>
<div id="header">
<div id="shortcutbar">
<a id="backBtn" onclick =="iframeBack();"></a>
<a id="forwardBtn" onclick =="iframeForward();"></a>
</div>
</div>
<div id="displayContainer">
<iframe id="display" src="https://website.goes.here/">
</iframe>
</div>
<script>
function iframeBack() {
$("#display").contentWindow.history.go(-1);
}
function iframeForward() {
$("#display").contentWindow.history.go(1);
}
</script>
</body>
Checking the console, I get the following error: Uncaught TypeError: Cannot read property "history" of undefined and it gives both whatever line the function is called in the HTML, and the line of the function itself in the script tags.
I'm at a loss of what isn't working, as everything I've found thus far just refers to some variation of what I've already typed.
The jQuery object doesn't have contentWindow property.
You need the underlying element ... $("#display")[0].contentWindow.
With that said if the iframe source is from a different origin than the main page you are security restricted from accessing the frame window using javascript
You can use postMessage also for secure communication
$("#display").contentWindow.postMessage('back');
window.addEventListener('message', ({ data }) => {
data === "back" && window.history.back()
});
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
This might sound like a silly question, and I tend to use:
$(document).ready(function() { });
But basic question.
Let's say I have a list of elements like this:
<body>
<p>Paragraph</p>
<div>Div</div>
<div id="HelloWorld">Hello, World</div>
<script>
var hw = $('#HelloWorld');
$(document).ready(function() {
// hw is available for me here
});
</script>
<p>Another paragraph</p>
</body>
It seems the div is available, and I don't run into errors, but is there anything technically wrong with this? Not talking perfectly organized code, but just curious about the technical question at hand.
So I suppose the question is:
Is a DOM element considered complete and available as soon as the browser reads it, regardless if the rest of the elements have loaded yet?
It seems the div is available, and I don't run into errors, but is there anything technically wrong with this?
No. As long as the script isn't run until after the element exists, you can access it. A script in a script tag that's after the markup for the element it refers to will consistently, cross-browser, be able to access that element.
Always works:
<div id="foo">...</div>
<script>
$("#foo")...
</script>
Never works:
<script>
$("#foo")...
</script>
<div id="foo">...</div>
Works only because jQuery delays executing the ready callback:
<script>
$(document).ready(function() {
$("#foo")...
});
</script>
<div id="foo">...</div>
This is one of the reasons for the common recommendation to put script tags at the end of the document, just before the closing </body> tag. That way, they have access to all of the elements defined above them. (And they don't delay the initial presentation of the page, which is usually, though not always, what you want...)
I'm having some difficulty with a Javascript function I am writing. The basic function of the script is that when a specific AJAX function is called and returns successful, it loads some HTML from a file and inserts that HTML into a on the main page and then (once loaded), fades in the parent div.
jQuery.ajax({
type: "POST",
url: "fns/authenticate.php",
data: dataString,
success: function (data) {
if (data=='1') {
jQuery("#authlogin").fadeOut(500, function(){
$(this).remove();
jQuery("#result").load("fns/logic.html", function() {
jQuery('#authtrue').fadeIn(1000);
});
});
} else {
jQuery('#details-error').fadeIn(200);
}
}
});
return false;
Now the AJAX seems to function properly, in that it will execute under the correct conditions and fade out and in the correct divs, the problem seems to be that the content isn't being loaded from logic.html or it is not being bound to the #result div correctly.
The main page's html looks like:
<div id="authlogin">
<!-- HTML form -->
</div>
<div id="authtrue" style="display: none;">
<div id="result"></div>
</div>
Any help would be much appreciated.
This is one of those things that you must troubleshoot yourself, because we do not have access to your fns/logic.html and therefore cannot test fully.
However, some thoughts:
(1) The basic logic of your .load() success function seems correct. Here is a jsFiddle that approximates the AJAX success function's logic. I substituted .html() for .load() because jsFiddle cannot do ajax. Anyway, assuming that .load() is doing what it should, that part should be working.
(2) You may already know this, but note that .load() is shorthand for $.ajax() -- as are .post() and .get(). You might find $.ajax() easier to troubleshoot as the code block is more structured. As a general rule, troubleshooting the shorthand constructions is slightly more abstract/difficult than troubleshooting $.ajax()
(3) Use developer tools in Chrome (press F12 key) to verify that the contents of logic.html have been inserted into the #result div. You might find, as I did in playing with my jsFiddle, that the contents were injected but the #authtrue div remained hidden. At least you will know that the logic.html document has been found and contents inserted. Knowing exactly where the problem is, finding/fixing the rest might now be trivial.
(4) Does your logic.html file include unnecessary header information? If so, you can strip it out by only inserting the BODY of the document, or a top-level containing div. See this section of the jQuery docs:
jQuery("#result").load("fns/logic.html #container", function() {//CALLBACK IN HERE});
(5) It would be a smart idea to create a test document that just and only loads the logic.html document, using various methods:
Method A: Using PHP (or whatever server-side language you use)
<div id="authlogin">
<!-- HTML form -->
<input type="button" id="mybutt" value="Click Me to Start" />
</div>
<div id="authtrue" style="display:none;">
<div id="result"><?php include 'logic.html'; ?></div>
</div>
Method B: Using load()
HTML:
<div id="authlogin">
<!-- HTML form -->
<input type="button" id="mybutt" value="Click Me to Start" />
</div>
<div id="authtrue" style="display:none;">
<div id="result"></div>
</div>
jQuery:
jQuery('#authtrue').show();
jQuery("#result").load("fns/logic.html");
(6) Ensure you do not have a typo in the destination element jquery selector: If no element is matched by the selector — in this case, if the document does not contain an element with id="result" — the Ajax request will not be sent. (from the docs)
I managed to fix this myself, thanks to the help of everyone here. It ended up being a browser caching problem. As soon as I cleared the cache everything magically worked.
This is sort of a condensed version of the code, the real version is too long to post but this is enough to represent the concept. I am using this to switch guitar diagrams based on several choices represented by anchors with the corresponding id in the href="". After spending several days getting it to work just right on a static html page, the script won't work in a Wordpress page which is where I intend to use it. I have tried it with the script in the head or inline (which shouldn't matter) - but either way it will not function. I know that Wordpress and certain plugins use Jquery so there may be a version mismatch causing conflicts. I am not (yet) an expert in javascript but I know there are several ways to skin a cat as the saying goes, I just need to find one that plays nice with Wordpress. Any help would be greatly appreciated...
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var divswitch = $('div.diagram_container a');
divswitch.bind('click',function(event){
var $anchor = $(this);
var ids = divswitch.each(function(){
$($(this).attr('href')).hide();
});
$($anchor.attr('href')).show();
event.preventDefault();
});
});
</script>
<style>
.diagram {
margin: 0;
width: 100%;
}
.diagram_container {
width: 100%;
}
</style>
<div id="RH_RW_Div" class="diagram_container" style="float:left; display:block;">
<div class="diagram_menu">
<a class="checked" href="#RH_RW_Div"><span class="checkbox_label">Right Handed</span></a>
<a class="unchecked" href="#LH_RW_Div"><span class="checkbox_label">Left Handed</span></a>
</div>
<img class="diagram" src='images/RH_RW.gif' /><br />
</div>
<div id="LH_RW_Div" class="diagram_container" style="float:left; display:none;">
<div class="diagram_menu">
<a class="unchecked" href="#RH_RW_Div"><span class="checkbox_label">Right Handed</span></a>
<a class="checked" href="#LH_RW_Div"><span class="checkbox_label">Left Handed</span></a>
</div>
<img class="diagram" src='images/LH_RW.gif' /><br />
</div>
Wordpress uses by default jQuery.noConflict(). This is to assure that there is no conflict by other libraries using the $ variable. That's why your console says it's not a function.
However, obviously, the jQuery variable still works, and you should use that, and passing to your function the $ variable yourself to enable the shorthand version of jQuery.
So your code should look like this:
jQuery(document).ready(function($){
// Your functions go here
});
My guess is that your Wordpress install or a plugin is already loading up jQuery in the head. Check to see if it exists there, and if it does, don't call it again.
If that doesn't do it and you have this site online, send me the link and I'll take a look.
Calling jQuery twice will often lead to problems. There is also a proper way to load jQuery and override the Wordpress version if you specifically need 1.8.3 (wp_register_script and wp_enqueue_script), but I don't think you need to go down that route yet.
Could you help me to understand - where I made the mistake. I have the following html code:
<div id="container">
Info mail.ru
</div>
<div id="container">
Info mail.com
</div>
<div id="container">
Info mail.net
</div>
and the following js code (using jQuery):
$('#getInfo').click(function(){
alert('test!');
});
example here
"Click" event fired only on first link element. But not on others.
I know that each ID in html page should be used only one time (but CLASS can be used a lot of times) - but it only should (not must) as I know. Is it the root of my problem?
TIA!
upd: Big thx to all for explanation!:)
Use a class for this (and return false in your handler, not inline):
<div id="container">
Info mail.ru
</div>
<div id="container">
Info mail.com
</div>
<div id="container">
Info mail.net
</div>
$('.getInfo').click(function(){
alert('test!');
return false;
});
http://jsfiddle.net/Xde7K/2/
The reason you're having this problem is that elements are retrieved by ID using document.getElementById(), which can only return one element. So you only get one, whichever the browser decides to give you.
While you must, according to the W3 specifications, have only one element with a given id within any document, you can bypass this rule, and the issues arising from the consequences if document.getElementById(), if you're using jQuery, by using:
$('a[id="getInfo"]').click(function() {
alert('test!');
return false;
});
JS Fiddle demo.
But, please, don't. Respect the specs, they make everybody's life easier when they're followed. The above is a possibility, but using html correctly is much, much better for us all. And reduces the impact of any future changes within the browser engines, jQuery or JavaScript itself.
It must only be used once or it will be invalid so use a class instead, return false can also be added to your jQuery code as so: -
$('.getInfo').click(function(){
alert('test!');
return false;
});
<a href="#info-mail.net" **class**="getInfo" ....
First id's are for one element only, you should have same id for several divs.
you can make it class instead.
your example changed:
<div class="container">
<a href="#info-mail.ru" class="getInfo" >Info mail.ru</a>
</div>
<div class="container">
<a href="#info-mail.com" class="getInfo" >Info mail.com</a>
</div>
<div class="container">
<a href="#info-mail.net" class="getInfo" >Info mail.net</a>
</div>
$('.getInfo').click(function(ev){
ev.preventDefault(); //this is for canceling your code : onClick="return false;"
alert('test!');
});
You can use the same id for several element (although the page won't validate), but then you can't use the id to find the elements.
The document.getElementById method only returns a single element for the given id, so if you would want to find the other elements you would have to loop through all elements and check their id.
The Sizzle engine that jQuery uses to find the elements for a selector uses the getElementById method to find the element when given a selector like #getInfo.
I know this is an old question and as everyone suggested, there should not be elements with duplicate IDs. But sometimes it cannot be helped as someone else may have written the HTML code.
For those cases, you can just expand the selector used to force jQuery to use querySelectorAll internally instead of getElementById. Here is a sample code to do so:
$('body #getInfo').click(function(){
alert('test!');
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<div id="container">
Info mail.ru
</div>
<div id="container">
Info mail.com
</div>
<div id="container">
Info mail.net
</div>
</body>
However as David Thomas said in his answer
But, please, don't. Respect the specs, they make everybody's life easier when they're followed. The above is a possibility, but using html correctly is much, much better for us all. And reduces the impact of any future changes within the browser engines, jQuery or JavaScript itself.