I have the below code. I'm trying to set a click event on the inner content of the iframe.
$(function(){
$("#popupIframe").load(function(){
var selection = $(this).find(".selectLocation").click(function(evt){
evt.preventDefault();
console.log("clicked");
});
console.log("this = ", $(this));
});
});
selectLocation is a class on a div element inside my iframe html. The above doesn't seem to work or at least the click event is not getting called. The console is tracing out the iframe selector.
This will only work on an iframe which has the same domain as the parent. Use contents() which you can then traverse just like any other object.
Example HTML:
<iframe id="fiddleframe" src="jsfiddle.net" width="400" height="400" />
Example JQuery:
$('#fiddleframe').contents().find('.pageHeader').css('border','3px solid red');
http://jsfiddle.net/AlienWebguy/Rbe2u/
UPDATE: A question was asked in the comments about using this practice on an iFrame that was created on the fly. To accommodate for JQuery-created iFrame, you need to ensure the iFrame's DOM has been loaded completely before you can apply any CSS manipulation.
$('#create').click(function(){
$('<iframe/>')
.attr({
id:"fiddleframe",
src:"jsfiddle.net",
width:"400",
height:"400"})
.appendTo('body')
.load(function(){
$(this)
.contents()
.find('.pageHeader')
.css('border','3px solid red');
});
});
http://jsfiddle.net/AlienWebguy/Rbe2u/1/
For anyone who is looking for the answer. This does not work for cross domain files.
$(function(){
$("#popupIframe").load(function(){
var $iframe = $(this.contentDocument||this.contentWindow.document);
$iframe.find(".selectLocation").click(function(evt){
evt.preventDefault();
console.log("clicked");
});
});
});
Thanks to HackedByChinese who posted it on this thread. How to find a div inside of an iframe
Related
I have used an image instead of button, now I want to disable the onclick() event in some case as we disable a button. I tried many ways but doesn't work. Below is what I did:
<img title="Ok" class="mtbtn"id="upd_1" onclick="add_edited('1','MM');" src="/project/images/green_ok.gif" border="0">
The jQuery code is:
$("#upd_1").css('opacity','0.5');
$("#upd_1").unbind("click");
I also tried:
$("#upd_1").css('pointer-events','none'); and document.getElementById('upd_1').style.pointerEvents = 'none';.
Any solution?
Try this:
$("#upd_1").on('click',function(e){
e.preventDefault();
});
One hint is that you can give your click event a suffix so you can be sure it's the only event you are affecting. To bind:
$('#elementId').on('click.myevent', function () {
// your code
}
To unbind:
$('#elementId').off('click.myevent');
Not going into binding or unbinding the click event but how about creating a mask for the image. Hide the mask when you want the image to be clickable else show it.
img onclick="alert('clicked')" src="http://lh3.googleusercontent.com/mjejVTJKT4ABNKq2HGlkDs36f-QvzI2hKFER098vBIgiAoZ2H-SN5QPvFaZEVDZRxfujrS6pszZ_J-_di2F57w0IFE3KAciDwGAh-9RcCA=s660" alt="" />
<div id="mask"></div>
<script>
$('#mask').hide();
$('#disable').click(function() {
$('#mask').show();
});
$('#enable').click(function() {
$('#mask').hide();
});
</script>
Try the Plnkr: Plnkr
Try this way. Add your parameters in two attributes (data-a and data-b for example).
<img title="Ok" class="mtbtn"id="upd_1" data-a="1" data-b="MM" src="/project/images/green_ok.gif" border="0">
Then change your javascript in this way:
$(document).ready(function(){
$("#upd_1").bind("click", function(){
var a = $(this).data("a");
var b = $(this).data("b");
// Code here
$(this).unbind("click");
});
});
Here the result.
Alternative is this:
var semaphore = true;
function add_edited (a, b) {
if (semaphore) {
semaphore = false;
// Code here
}
}
Create a semaphore to manage the execution of the code to the click.
i understood you'r problem, there is no need to unbind() and re bind() the onclick event, you can simply remove and re-add onclick attribute using removeAttr() and attr()
<img title="Ok" class="mtbtn"id="upd_1" onclick="add_edited('1','MM');" src="/project/images/green_ok.gif" border="0">
JQuery:
$("#upd_1").css('opacity','0.5');
$("#upd_1").removeAttr('onclick');
to re add onclick event do the following:
$("#upd_1").css('opacity','1');
$("#upd_1").attr("onclick","add_edited('1','MM');");
that is all you need to do.
I'm adding a Chatango HTML5 chat box to my website, but when users scroll up or down in the chat box, it also scrolls up or down the rest of the page. I've been experimenting with different codes I've found on this site, but so far nothing has worked.
I thought I found a solution here: How to disable scrolling in outer elements? and applied it to my chatroom. It works exactly how I want it to on this codepen editor: http://codepen.io/EagleJow/pen/QbOBJV
But using the same code in JSFiddle: https://jsfiddle.net/4bm6ou90/1/ (or on my actual website) does not prevent the rest of the page from scrolling. I've tested it in both Firefox and Chrome with the same results.
Here's the javascript:
var panel = $(".panel");
var doc = $(document);
var currentScroll;
function resetScroll(){
doc.scrollTop(currentScroll);
}
function stopDocScroll(){
currentScroll = doc.scrollTop();
doc.on('scroll', resetScroll);
}
function releaseDocScroll(){
doc.off('scroll', resetScroll);
}
panel.on('mouseenter', function(){
stopDocScroll();
})
panel.on('mouseleave', function(){
releaseDocScroll();
})
Any ideas?
It didn't work on JSFiddle because I didn't have jQuery set on the side menu and it didn't work on my website because the '$' symbol in the javascript conflicted with that same symbol in the jQuery (or something like that).
Here's the JSFiddle with better code and set to load jQuery: https://jsfiddle.net/4bm6ou90/7/
The Javascript:
$.noConflict();
jQuery( document ).ready(function( $ ) {
$(".panel").on("mouseenter", function(){
$(document).on("scroll", function(){
$(this).scrollTop(0);
});
});
$(".panel").on("mouseleave", function(){
$(document).off("scroll");
});
});
Also gotta have that jQuery CDN in the html head section.
Here is fiddle example of something I would like to do. I want to mouse over element that is inside iframe (same domain) and then change color of the font. Like in example.
But in my version first the iframe is created after I push the button - my fiddle example. In my example mouseover wont work and I do not know why. I am not that experienced with JavaScript and can not figure it out on my own. Maybe what I want to do cannot be done or maybe I'm just missing something out.
function load_iframe(callback) {
$('#iframe').append('<iframe class="ajax" scrolling="no" style="height:190px" src="http://fiddle.jshell.net/38g2pyxh/"></iframe>')
$('.ajax').load(function() {
callback(this);
});
}
$(document).on('click','#create',function(callback){
load_iframe(function(){
iframe = $('iframe.ajax').contents()
iframe.find('body').prepend('<b>This is a test</b><br><b>Click here</b>');
})
return iframe
})
iframe.on('mouseover', 'b', function() {
$(this).css('color','red');
});
What I have done so far: Fiddle
this is simple code i hope to help you .... i am edit your code
var iframe
var a
function load_iframe(callback) {
$('#iframe').append('<iframe id="1a" class="ajax" scrolling="no" style="height:190px" src="http://fiddle.jshell.net/38g2pyxh/"></iframe>')
$('.ajax').load(function() {
callback(this);
});
}
$(document).on('click','#create',function(callback){
load_iframe(function(){
iframe = $('iframe.ajax').contents()
iframe.find('body').prepend('<b id="bb">This is a test</b><br><b>Click here</b>');
a=document.getElementById('1a').contentWindow.document.getElementById('bb')
alert('pass')
a.onmouseover=function(){
a.style.color="red"
}
a.onmouseleave=function(){
a.style.color="black"
}
})
return iframe
})
I've checked other posts on here, no results of what I'm looking for.
I want to click on
About
<div id="about">Content of this..</div>
and have it scroll to that element without putting www.domain.com/#about in the address bar
As a perfect example please check out this site that I found here and click on some of the links --they don't change the address bar when clicked.
You can do what you want using javascript and jquery, example below (note that this is using an old version of jquery):
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type='text/javascript'>
jQuery(document).ready(function($) {
$(".scroll").click(function(event){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 1200);
});
});
</script>
</head>
<body>
<a class="scroll" href="#codeword">Blue Words</a>
<div id="codeword"></div>
</body>
</html>
Played around with this myself and here is a summary of my learnings on the subject.
Here's the basic link command:
Blue Words
Here's how you denote where the jump will scroll the page:
<A NAME="codeword">
Here's what's happening
The A HREF command is the same as a basic link except the link is to a codeword rather than a URL.
PLEASE NOTICE there is a # sign in front of the codeword. You need that to denote it is an internal link. Without the # sign, the browser looks for something outside the page named after your codeword.
Your "codeword" can be just about anything you want. I try my best to keep it short and make it denote what it is jumping to. There might be a limit to the number of letters you can use--but I haven't found it yet.
The point where the page will jump follows the same general format except you will replace the word HREF with the word NAME.
PLEASE NOTICE there is no # sign in the NAME command.
Note! Where you place the NAME target will appear at the top of the screen browser.
Hope it helps.
window.location.hash = ""
is the possible way I could find.
hash gives the string next to #.
//dont use a, use class
$(document).ready(function(){
$(".mouse").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes
to scroll to the specified area
$('html, body').animate({
scrollTop: $("#section").offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = "";
});
} // End if }); });
One possible workaround is to use a <button> instead of a <a>.
So rather than....
About
<div id="about">Content of this..</div>
...you can change it to
<button href="#about">About</button>
<div id="about">Content of this..</div>
This way the anchor link will not affect the URL.
For me, only inserting "return false;" solved this issue.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" async></script>
<script>
jQuery(document).ready(function($) {
$('a[href^=#]:not(a[href=#])').click(function() {
$('html, body').animate({scrollTop: $(this.hash).offset().top}, 1300, 'easeInOutExpo');
return false;
});
});
</script>
(This applies to all anchor links on the page.)
I tried to monitor window.location.hash using a MutationObserver, but that doesn't work, see How to use (or is it possible) MutationObserver to monitor window.location.pathname change?
So now I'm using the window.onpopstate() eventListener:
var flag_onpopstate=false; // use this global flag to prevent recursion
window.onpopstate = () => {
if (flag_onpopstate) return;
flag_onpopstate = true;
window.location.hash = "";
flag_onpopstate = false;
}
A popstate event is dispatched to the window each time the active history entry changes between two history entries for the same document.
How can I prevent the page from "jumping up" each time I click a link? E.g I have a link somewhere in the middle of the page and when I click it the page jumps up to the top.
Is the anchor href="#"? You can set it to href="javascript:void(0);" instead.
If you are going to a prevent default please use this one instead:
event.preventDefault ? event.preventDefault() : event.returnValue = false;
Let's presume that this is your HTML for the link:
Some link goes somewhere...
If you're using jQuery, try like this:
$(document).ready(function() {
$('a#some_id').click(function(e) {
e.preventDefault();
return false;
});
});
Demo on: http://jsfiddle.net/V7thw/
If you're not on jQuery drugs, try with this pure DOM JavaScript:
window.onload = function() {
if(document.readyState === 'complete') {
document.getElementById('some_id').onclick = function(e) {
e.preventDefault();
return false;
};
}
};
It will jump to the top if you set the link href property to # since it is looking for an anchor tag. Just leave off the href property and it won't go anywhere but it also won't look like a link anymore (and make sure to handle the click even in javascript or else it really won't be of much use).
The other option is to handle the click in javascript and inside your event handler, cancel the default action and return false.
e.preventDefault();
return false;