I am binding the scroll events to all my html elements. To get the all the elements i am using the below filter
var element = $(myelemt).parentsUntil("html").add($(window));
return element
here element will return the body, window and all parents htmls tags.
For this html elements i am binding the events like below code:
element.on("scroll", function (e) {
$("#mywrapper3").html($("#mywrapper3").html() + "scrolling<br>");
}
Here i want to prevent particular child div element only from binding. How i can achive this?.
For example in my page for one div element(element with mywrapper id in sample) i dont want to bind this scroll event.
Also, I have to filter the element like in first code only. So how to achieve this instead of using stop propagation. Is there any way to do this.
I have prepared the one jsfiddle.Please get the link below
https://jsfiddle.net/khkcjb6o/
Thanks for any help
The .off() method is what you need. Originally I had started answering with an iframe solution and came up with the better solution later.
Since an iframe's context is different than it's parent, it is not included if you register everything on the parent page.
In the PLUNKER, the first section has an iframe with srcdoc and content within. Scroll the iframe and you'll notice that it isn't triggering the scroll counter.
Same thing with the second section that has a normal iframe.
The third and fourth section have scrolling content.
As expected, both trigger the scroll event.
Click the IV OFF button which uses the .off() method.
Now scroll section IV and notice the scroll counter isn't increasing.
.off() is what you need. Make sure to use this expression:
$('*').on('scroll', function() {....
That * will register everything but iframe content on a page so you don't have to write all of that code you had in your question.
You could jus use the :not() CSS selector
var element = $(myelemt + ':not(#mywrapper3)').parentsUntil("html").add($(window));
element.on("scroll", function (e) {
$("#mywrapper3").html($("#mywrapper3").html() + "scrolling<br>");
}
Related
I am using the google search API and I want that when you click on an image, this image will be copied to a different location.
I created a fiddle here: http://fiddle.jshell.net/wjewg062/
It works this way: The user types in a term in the input field and images will be displayed. When he/she clicks on one twice it will displayed in the image div.
I put the onClick event listener on to the searchresults div, hence the extra click in the beginning. However, I want it to be displayed on the first click.
Now, if I comment this out
var searchresults = document.getElementById('searchresults');
searchresults.addEventListener("click", function(event){
event.preventDefault();
imageing();
});
it doesn't work. The images will be links. I believe the reason for this is that the results are displayed in gs-image-box and not created yet. I tried calling the imaging function in different other functions like the searchImg or the OnLoad but nothing work.
I thought of using a check if element is clicked function described here Detect if I'm clicking an element within an element
but I think there must be an easier way.
I'm running out of ideas, can anyone give an idea or hint?
Thanks !
The images are dynamically created right? Check out this post Event binding on dynamically created elements?
In short, events are attached to elements upon pageload. so a newly created dynamic element such as the ones that google creates, aren't attached to the event. so google probably has a way to circumvent the whole "you need to load the page to attach events to elements" thing but it requires an extra click. Using the syntax found in the post should help you.
By the way. Using Jquery doesn't really show down your site because it's usually cached in the client's browser.
The info you need is already in your searchresults eventListener. The target of this event will be the image you click, even if you add the event on a div higher in the structure.
A javascript event will by default be dispatched from the top element (window) all the way through the element that received the click, then will go back to the top. Any element that is an ancestor of the element that was clicked will receive the event info, so you can listen on any ancestor, but the target remains the element that was actually clicked.
In your case, by simply passing the target to your imageing() function, you can apply the behaviors you want without any extra manipulations.
One problem you might face, is if user clicks on searchresult but not on an img element. Then you'll have a bug, so you should handle these cases.
Something like this:
var searchresults = document.getElementById('searchresults');
searchresults.addEventListener("click", function (event) {
console.log(event.target, this);
event.preventDefault();
if(event.target.tagName == 'IMG'){
imageing(event.target);
}
});
function imageing(targetImg) {
var imageresult = document.getElementsByClassName('gs-image-box');
var xu = document.getElementById('companylogo');
var imgsrc = targetImg.src;
xu.src = imgsrc;
}
http://fiddle.jshell.net/pwjLrfnt/3/
Have a really strange issue that a colleague was facing which I managed to work around, but for the life of me cannot understand why his initial code did not work! - we have a legacy asp.net web application that is using MasterPages/Content controls and has jQuery mixed all over the web application providing some client interactivity.
Essentially there is a web form view that has a div containing a button which is initially hidden (display: none), upon clicking another menu item, this div is shown using jQuery BLOCKUI Plugin, blocking the rest of the UI and rendering the popup div into place - the user can then click the button, clicking the button should hide the containing div, and show another div that contains another two buttons - all should be simple.... but this is where it got funky:
Bear in mind none of this content is dynamically generated, all HTML elements are present within the .aspx view up front after the page is finished loading.
var blockUiRenderFrame = function (html, width, height) {
window.parent.$.blockUI({
message: html,
css: {
top: ($(window.parent).height() - height) / 2 + 'px',
left: ($(window.parent).width() - width) / 2 + 'px',
width: width
}
});
};
<div id="anotherContentFrame">
<p>some text</p>
</div>
<div id="contentFrame" style="display:none;">
<div id="myButtonContainingDiv">
<button id="aButton" />
</div>
<div id="myOtherButtonsContainingDiv"></div>
</div>
$(document).ready(function() {
$("#myButton").click(function() {
$("#myButtonContainingDiv").hide();
$("#myOtherButtonsContainingDiv").show();
});
});
<!-- A Button on the page calls this code -->
blockUiRenderFrame($("#contentFrame"), 200, 200);
What I observed occurring was what appears to be a complete loss of context, or executing the event under a different context all together... during the handling of the click event, the div elements, or indeed anything within the HTML div contentFrame all return undefined.
At any other time if I use the console/debugger, I can successfully return an element using say $("#myButtonContainingDiv").
The click event has its correct event element, I can use $(this) to get the button I clicked on, but even trying to select $("#myButton") within the actual click event handler code itself returns 'undefined'.
I can access $("anotherContentFrame") perfectly fine, at any time, including during the handling of the click event of #myButton.
The workaround I had to use in order to get this code to work was:
During the click event handler, use the following:
$(this).closest('div').hide()
$(this).closest('div').next().show()
As this was the only way I could get any reference to the DOM elements on the page to successfully hide/show them.
I can try to give out some more information if anyone wishes, I am not sure if anyone has ever seen an issue like this.
Thanks in advance!
Where's the code showing your button?
When you call $(element).click() it will try to bind to your element on the DOM that is already loaded (no async elements!). If you're loading the #myButton via a async call, you need to bind the click on a parent element and then filter the function call to your #myButton like this:
$(document).on('click', '#myButton', function(){});
This way you're sure that the element (in this case, document) existing when jQuery tries to bind the click event and it will only fire it when clicking on the filter you specified as the 2nd parameter to the .on() call, in this case, your #myButton element
Your event is not firing because jQuery doesn't know the element, because its state changed dynamically. In order to be sure to fire your click event, no matter the context, you can use
$(document).on('click', '#myElement', function(){});
By doing that, you are refering to the easiest "non dynamically generated" element, and jQuery will always be able to find your element.
You can then access your element properties with :
$(this)
I have written my custom element in Polymer. The element has a lot of child elements. And I would like to detect scroll event of the element so I can lazyload some content into it. Is it possible somehow ?
Try:
HTML:
<CUSTOMELEMENT onscroll="scrollHandler">
...child elements here...
</CUSTOMELEMENT>
JS:
function scrollHandler(){
console.log("scrolled!");
}
Look if this element of polymer can be useful for you, https://www.polymer-project.org/docs/elements/core-elements.html#core-scroll-threshold in any case, without an expample of the code you are using, it is dificult to know exactly what is happening, also a Jsbin could be great
You can add a scroll event listener to your element:
listeners: {
'scroll': '_userDidScrollFullElement',
},
This code will trigger the function _userDidScrollFullElement function on your Polymer element when the user scrolls.
If you want to be more specific and want to only trigger the function when the user scrolls a sub-element you can do the following:
listeners: {
'your__element__id.scroll': '_userDidScrollSpecificElement',
},
This code will trigger the function _userDidScrollSpecificElement function on your Polymer element only when the user scrolls the sub-element with id your__element__id.
For more information on events you can check the Polymer Events page.
i have one page and i have written code
i am using jquery. now i want to append some html elements in some div of FormView.jsp, in response to some of the event fired in showFormPage.jsp.
how can i do it?
help me..
In your event handler you can target a element ID of say section in another frame called say other_frame, like so:
$("#button").click(function() {
$("#section", top.frames["other_frame"].document).append("<b>your html elements</b>");
});
Is it possible, with Javascript or some other technology to determine which hyperlink a user has clicked on, without changing the hyperlink source code.
For example:
Can you click on a 'tag' button, then click on a hyperlink hosted in a different iframe, and be able to calculate which hyperlink the user clicked on, without changing any of the source code in that iframe?
Using jQuery, you are able to set the context of your selection. i.e.
$('a', $('#iframe-id')).click(function() {...});
You can then implement an event handler that will handle the iFrame hyperlink clicks. The "this" property within the handler will allow you to interrogate the hyperlink and obtain properties such as innerText etc.
you need to put an event on each a link ,
and then you will get all the information about the specific click.
this will work only in the some document,
so if you try to do a test between the link inside an iframe and a link in your page you will not get an event for the iframe link.
in order to attach the event for all link you need to run on all the links in the page ,
the best way to do that is by jQuery selector. or other js framework like YUI
$("a").click(function () {
alert('')
});
getElementsByTagName("a") - will give you all the links in the page.
I just thought of a solution, would this work, or are there other options?
The solution would be to proxy the content of the iframe soruce page, replacing href's with code to call a javascript function which would identify which href was clicked on.
This could then be used in conjunction with the tag'ing click to accurately tag a link.
This would also mean the original source, doesn't need to change at all.
What do you need ?-)
If you got an iframe, you use as a target for links, you must do some server-side processing or add something to the url of the links, that you can read when the page loads ...
But detecting time of page-load requires a script in the page, that is inside the iframe, or a function which tests the availability of the elements in the page in the iframe in short intervals ...
-- but you can only succeed if the page comes from the same domain as the main-page, as cross-domain scripting is illegal and thus impossible !-)
I think it should be possible. The contents of an IFrame is accessible from the outer document (the page in which the iframe is embedded) so you should be able to add event handlers (see other answers) on those elements after the iframe has loaded.
See also Wikipedia on Iframe which gives some examples and frameworks which actually work on content within an IFrame.
You can inject code into an iframe, but only if that iframe is on the same domain as the page you're injecting from, for obvious security reasons.
<iframe id="framedpage" src="framedpage.html"></iframe>
<button type="button" id="tagbutton">Tag</button>
<script type="text/javascript">
function framedclicks_bind() {
var f= document.getElementById('framedpage');
var fdoc= f.contentDocument;
if (!fdoc) fdoc= f.contentWindow.document; // for IE
if (fdoc)
for (var i= fdoc.links.length; i-->0;)
fdoc.links[i].onclick= framedclicks_click; // bind to all links
}
function framedclicks_click() {
alert('You clicked on '+this.href);
return false; // don't follow link
}
document.getElementById('tagbutton').onclick= framedclicks_bind;
</script>
Might want to cleaning-up depending on application needs (eg. to ensure the frame is always loaded before trying to bind, or that unbinding can happen, or that any onclicks from the original links are remembered), but that'd be the general shape of things.
Good solution to find out which element was clicked is to use event delegation. If you attach event listener to each element using a loop (over document.links or document.getElementsByTagName), you have two problems:
- browser has many listeners to maintain
- events are attached only to elements that were in the DOM when you called the loop; any element dynamically added later doesn't have an event listener.
A simple example of event delegation:
document.onclick = function(e){
e = e || window.event;
var t = e.target || e.srcElement;
if(t.nodeName=='A'){
alert( t.href );
}
}
If you want to find clicked link inside an iframe just use iframe's contentDocument instead of document.