HTMLObjectElement onclick event doesn't fire [duplicate] - javascript

I want to add a click event to an iframe. I used this example and got this:
$(document).ready(function () {
$('#left').bind('click', function(event) { alert('test'); });
});
<iframe src="left.html" id="left">
</iframe>
But unfortunately nothing happens.
When I test it with another element (e.g. a button), it works:
<input type="button" id="left" value="test">

You could attach the click to the iframe content:
$('iframe').load(function(){
$(this).contents().find("body").on('click', function(event) { alert('test'); });
});
Note: this will only work if both pages are in the same domain.
Live demo: http://jsfiddle.net/4HQc4/

Two solutions:
Using :after on a .iframeWrapper element
Using pointer-events:none; one the iframe
1. Using :after
use a transparent overlay ::after pseudo element with higher z-index on the iframe's wrapper DIV element. Such will help the wrapper to register the click:
jQuery(function ($) { // DOM ready
$('.iframeWrapper').on('click', function(e) {
e.preventDefault();
alert('test');
});
});
.iframeWrapper{
display:inline-block;
position:relative;
}
.iframeWrapper::after{ /* I have higher Z-index so I can catch the click! Yey */
content:"";
position:absolute;
z-index:1;
width:100%;
height:100%;
left:0;
top:0;
}
.iframeWrapper iframe{
vertical-align:top;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="iframeWrapper">
<iframe src="http://www.reuters.tv/" frameBorder="0"></iframe>
</div>
2. Using pointer-events:none;
Clicks are not handleable from outside the iframe from an external resource (if the iframe is not in your domain).
You can only create that function inside your 'called into iframe' page, not from within the iframe-hosting page.
How to do it:
You can wrap your iframe into a div
make the click "go through" your iframe using CSS pointer-events:none;
target clicks with jQuery on your wrapping DIV (the iframe parent element)
jQuery(function ($) { // DOM ready
$('.iframeWrapper').on('click', function(e) {
e.preventDefault();
alert('test');
});
});
.iframeWrapper{
display:inline-block;
position:relative;
}
.iframeWrapper iframe{
vertical-align:top;
pointer-events: none; /* let any clicks go trough me */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="iframeWrapper">
<iframe src="http://www.reuters.tv/" frameBorder="0"></iframe>
</div>
NOTA BENE:
No clicks will be registered by the iframe element, so a use-case would be i.e: if by clicking the iframe you want to enlarge it full screen.... Etc...

I got it to work but only after uploading it to a host. I imagine localhost would work fine too.
outer
<html>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function() {
var myFrame = document.getElementById("myFrame");
$(myFrame.contentWindow.document).find("div").on("click", function () { alert("clicked"); });
});
</script>
<body>
<iframe id="myFrame" src="inner.htm"></iframe>
</body>
</html>
inner
<html>
<head>
<style>
div {
padding:2px;
border:1px solid black;
display:inline-block;
}
</style>
</head>
<body>
<div>Click Me</div>
</body>
</html>

Pure Javascript
Not my solution but only this works well.
let myConfObj = {
iframeMouseOver : false
}
window.addEventListener('blur',function(){
if(myConfObj.iframeMouseOver){
console.log('Wow! Iframe Click!');
}
});
document.getElementById('YOUR_CONTAINER_ID').addEventListener('mouseover',function(){
myConfObj.iframeMouseOver = true;
});
document.getElementById('YOUR_CONTAINER_ID').addEventListener('mouseout',function(){
myConfObj.iframeMouseOver = false;
});

$(document).ready(function () {
$('#left').click(function(event) { alert('test'); });
});
<iframe src="left.html" id="left">Your Browser Does Not Support iframes</iframe>
The script would have to be ran entirely from the iframe. I would recommend a different method of calling content, such as php.
iframes aren't really worth the hassle.

The actual problem is that, the click event does not bind to the DOM of the iframe and bind() is deprecated, use .on() to bind the event. Try with the following codes and you will find the borders of the iframe clickable getting that alert.
$('#left').on('click', function(event) { alert('test'); });
Demo of that Issue
So how to get it done?
How you should do is, create a function on iframe page, and call that function from that iframe page.

Related

Show/Hide Div by clicking another div

I am a beginner at javascript and I wrote a simple code trying to show/hide a div simply by clicking on another div. If someone can check the code I wrote and correct me I would be really grateful. Thanks in advance.
$('DivBlue').ready(function() {
$('DivRed').on('click', function(){
document.getElementById('DivBlue').style.display = 'block';
});
});
.DivRed{
position:absolute;
top:0;
left:0;
width:15vw;
height:15vw;
background-color:red;
}
.DivBlue{
position:absolute;
display:none;
right:0;
bottom:0;
width:15vw;
height:15vw;
background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="DivRed"></div>
<div class="DivBlue"></div>
You can do this with the toggle() function in the jQuery library. toggle() with no arguments is a to shortcut show/hide an DOM element.
Also, it is good practice to use .ready() on the document instead of an element of the DOM.
So, your JS code should look like:
$(document).ready(function() {
$('.DivRed').on('click', function(){
$('.DivBlue').toggle();
});
});
DEMO
Toggle does the trick in jQuery:
$(document).ready(function() {
$('.DivRed').on('click', function() {
$('.DivBlue').toggle();
});
});
Replace your JavaScript with this and it will surely work.
$(document).ready(function() {
$('.DivRed').click(
function() {
$('.DivBlue').toggle();
});
});
You are making few mistakes here,
You cant get a div by a class name with document.getElementById() method. You need to use document.getElementsByClassName() method.
document.getElementsByClassName() return a NodeList. You can't apply CSS for a NodeList. So you need to select a Node to apply CSS using document.getElementsByClassName('DivBlue')[0]
To work your code should be changed as
$('DivBlue').ready(function() {
$('DivRed').on('click', function(){
document.getElementsByClassName('DivBlue')[0].style.display = 'block';
});
});

Selector $(body) works but break the code (reference error) while $("body") shows no error but dont work

I have a JS function that I need to be called on window resize.
The only way I found to get this working is by using:
$(body).on('resize', function(){
myFunction();
});
With this, myFunction() is executed on window resize.
The problem is that I get a reference error (body is not defined), so the rest of my JS isn't executed properly.
I tried different selectors: $("body"), $("document.body"), $(window), $(document),... With them I get no reference error, but the function is not executed.
Here's what looks like ( minimal view ) my html:
<html>
<head>
<script src="jquery.js"></script>
</head>
<body>
[ Alot of things ...]
<script src="main.js"></script>
</body>
</html>
So, jQuery is included in my head section, while my JS is included before closing body tag.
Now this is what looks like my main.js file:
myFunction(){
alert("Hello world");
}
$(body).on('resize', function(){
myFunction();
});
$(document).ready(function(){
myFunction();
}
Function works properly on page load ( with $(document).ready ) but I need it to run on each page resize.
I searched a lot to solve my problem, but I'm stuck. I apologize if the answer is trivial. I'm kind of a noob with JS and DOM elements selectors.
Edit with some more infos:
The function in question is used to set multiple div to an equal height.
You can found it here Equal Height divs with jQuery.
My div group are rows of skelJS grid system.
So the initial problem was that when i was resizing my window, divs where not resized to fit the responsive font-size, so I get an overflow.
Obviously I tried to call that function on window/body resize, but I can't get it to work EXCEPT if I use $(body) selector, which gives me an reference error, but then the overflow problem disappear and function properly runs on resize.. It's really strange. I tried all of your solutions, nothing seems to work.
You should be attaching the resize to the window, not to the document.body.
(function() {
function resizeFnc() {
console.log("resized called");
}
$(window).on("resize", resizeFnc); //calls it on resize
$(resizeFnc); //calls it on document ready
}());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The reason why $(body) fails is there is no variable "body" declared. The reasn why $("body") and $(document.body) fail is the event is not triggered on the body so it is not called.
And with the code you linked to.
function equalHeight(group) {
console.log("I was called");
tallest = 0;
group.each(function() {
thisHeight = $(this).height();
if(thisHeight > tallest) {
tallest = thisHeight;
}
});
group.height(tallest);
}
$(function(){
equalHeight($(".EqHeightDiv"));
});
$(window).on("resize", function(){
console.log("resized called");
equalHeight($(".EqHeightDiv"));
});
.EqHeightDiv { width: 30% ;box-sizing: border-box; display: inline-block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="EqHeightDiv" style="float:left;border:solid 1px #ccc;margin:10px;">Here is some stuff</div>
<div class="EqHeightDiv" style="float:left;border:solid 1px #ccc;margin:10px;">Here is some stuff<br />Here is some stuff</div>
<div class="EqHeightDiv" style="float:left;border:solid 1px #ccc;margin:10px;">Here is some stuff<br />Here is some stu<br />Here is some stuff</div>
Now what is broken is the script you are using. Resize is called, it just is not setting the new max height. So as stated window resize is being triggered, the problem was somewhere else.
So how do we fix this?
var timer;
function equalHeight(group) {
if (timer) window.clearTimeout(timer); //so this code is not called on every single resize
timer = window.setTimeout( function () {
var tallest = 0;
group.height(""); //reset the heights
group.each(function() {
thisHeight = $(this).height();
if(thisHeight > tallest) {
tallest = thisHeight;
}
});
group.height(tallest);
}, 10);
}
$(function(){
equalHeight($(".EqHeightDiv"));
});
$(window).on("resize", function(){
equalHeight($(".EqHeightDiv"));
});
.EqHeightDiv { width: 30% ;box-sizing: border-box; display: inline-block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="EqHeightDiv" style="float:left;border:solid 1px #ccc;margin:10px;">Here is some stuff</div>
<div class="EqHeightDiv" style="float:left;border:solid 1px #ccc;margin:10px;">Here is some stuff<br />Here is some stuff</div>
<div class="EqHeightDiv" style="float:left;border:solid 1px #ccc;margin:10px;">Here is some stuff<br />Here is some stu<br />Here is some stuff</div>
Try this. Window is a global object and should not have any reference error
function myFunction(){
alert("Hello world");
}
$(window).resize(function() {
myFunction();
});
$(document).ready(function(){
$(window).on('resize', function(){
myFunction();
});
});
Here it is in action: https://jsfiddle.net/6t987c28/
If you are looking to change or add a class to <body>, then it should be done in your function instead of the resize jQuery:
$(window).on('resize', function() {
myFunction();
});
function myFunction() {
$('body').css('background', 'green');
// or
$('body').addClass('selector-name');
}

Page Loader in html page

I am trying to show a loader GIF image in the div section of this html page. But I can't get it to work. The div content is hidden and the GIF image disappears.
CSS:
.loader {
background-image: url(image/Preloader_8.gif);
background-repeat: no-repeat;
height:100px;
width:200px;
}
JavaScript:
<script type="text/javascript">
$(window).load(function() {
$(".loader").fadeOut("slow");
})
</script>
Html:
<body>
<div class="loader">
Loading Image
</div>
</body>
Are you using AJAX to fetch the content in div or simply .load function?
In case of .load() jQuery event,
$( ".loader" ).load( "test.html", function() {
$(".loader").fadeOut("slow");
});
In case of AJAX request, call the function loader in success event of AJAX call.
function loader() {
$(".loader").fadeOut("slow");
});
HTML
<body>
<div class="loader" style="display:none">
Loading Image
</div>
</body>
js
$(window).load(function() {
$(".loader").fadeOut("slow");
})
Please add the following script on the top of your web page
$(".loader").fadeIn();
Add loading div on top of just above script
I think the reason why your code:
$(window).load(function() {
$(".loader").fadeOut("slow");
})
didn't work is because the script is executed after the document is fully loaded.
Following code works.
if (document.readyState == 'complete') {
$(".loader").fadeOut("slow");
} else {
$(window).load(function () {
$(".loader").fadeOut("slow");
})
}
jsfiddle
In your code, the loader class is assigned to the div section, so when you trigger the fade out of the loader page, the entire div assigned to the class fade's out. So better have internal div to which the loader is assigned. This may help check out
<body>
<div class="Image">
<div class="loader">
Loading Image
</div>
</div>
</body>
Working example here
The simplest way of showing loader.gif on web page as:
<div id="divloader" class="ShowLoader">
<img id="imgUpdateProgress" class="loaderIMG" src="../../images/newloader.gif" alt="Loading ..." title="Loading ..." />
</div>
CSS code
<style>
.loaderIMG {
padding: 10px;
position: fixed;
top: 45%;
left: 45%;
width: 80px;
}
.HideLoader {
display: none;
}
</style>
jQuery code:
$(document).ready(function () {
$("#divloader").addClass("HideLoader");
});
First check that your jQuery library working or not by showing alert msg, and then check that image path from browser inspect element.
Add this code:
$(document).ready(function(){
$(".loader").fadeOut("slow");
})
jsfiddle

jQuery and CSS div element change

Right now i am working a simple jQuery code when a click on button a jQuery function is called and inside this function i change css of a div.
Here is my code, take a look:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function SuperWebF1()
{
$("#outerdiv").css({"border":"2px solid #e39f9f"});
alert('SportsDirect.bg: Моля, първо посочете желания от Вас цвят!');
}
</script>
<button type="button" onclick="billing.save();SuperWebF1();"></button>
<div id="outerdiv"></div>
CSS of "outerdiv":
#outerdiv
{
width:4000px;
height:300px;
overflow:hidden;
position:relative;
border:2px solid #fff;
}
When i place the alert('SportsDirect.bg: Моля, първо посочете желания от Вас цвят!'); before the $("#outerdiv").css({"border":"2px solid #e39f9f"}); the alert is working. But it's not working in the other way.
In all cases my CSS function is not working and this code is not changing the border CSS of the div element.
Where is my mistake guys?
After this code i also have:
<script type="text/javascript">
$.noConflict();
jQuery(document).ready(function($){
$("#SubmitButton").click(function() {
$('.HeaderPostForm').hide();
$('.PleaseWait').show();
this.form.submit();
});
});
</script>
I'm giving this as a note..
rather than using onclick why not add an event listener to the button by giving it an id and using that like so
<button type="button" id="btn">Button</button>
<div id="outerdiv"></div>
$("#btn").on("click", function(){
$("#outerdiv").css({"border":"2px solid #e39f9f"});
alert('SportsDirect.bg: Моля, първо посочете желания от Вас цвят!');
// and add the functionality for the other click event in here too
});
jsfiddle showing it in action using this method

Javascript- creating element as a child of another element

Hello here's my simple code.I want to display image created in function add(src){} in element main_container.Why doesn't it work?
<head>
</head>
<body>
<style>
#main_container
{
width:1000px;
height:1000px;
position:absolute;
border-style:solid;
}
.jersey
{
width:100px;
height:150px;
position:absolute;
}
</style>
<script>
var dist=-110;
function add(src)
{
dist=dist+110;
var img=document.createElement("img");
img.src=src;
img.style.left=dist+"px";
img.className="jersey";
document.getElementById("main_container").appendChild(img);
}
add("http://www.hdwallpapers.in/walls/abstract_color_background_picture_8016-wide.jpg");
</script>
<div id="main_container"></div>
</body>
</html>
Move the script tag below the element.
Change:
<script>...</script>
<div id="main_container"></div>
To:
<div id="main_container"></div>
<script>...</script>
The browser reads HTML from top to bottom.
beautifulcoder's suggested modification should work, and he is absolutely correct that this is happening because the main_container DOM element will not yet be loaded if it appears after the <script>, but ideally, you should hold off on making DOM manipulations until the document has loaded. You can do this by using the window.onload event:
<script>
function add(src) {
...
}
function initialize() {
add("http://www.hdwallpapers.in/walls/abstract_color_background_picture_8016-wide.jpg");
}
window.onload = initialize;
</script>
<div id="main_container"></div>
or even better, use jQuery's ready event:
function initialize() {
add("http://www.hdwallpapers.in/walls/abstract_color_background_picture_8016-wide.jpg");
}
$(document).ready(initialize);
// $(initialize); <- Shorthand version
Either of these approaches will free you from having to worry about where your script blocks are relative to your page elements.

Categories