How to attach a Click handler to a DOM element - html

How do I get a DOM element and attach an event onClick?. I tried this code but it does not work:
<div>
<h1 id="some_id">
click here
</h1>
</div>
JavaScript:
Ext.onReady(function() {
if(Ext.getDom('some_id'))
{
var elDom = Ext.getDom('some_id');
elDom.on('click', function(){
Ext.Msg.alert('Status', 'Already get the element from the dom');
});
}
});
Fiddle: https://fiddle.sencha.com/#fiddle/2fl

Another way to do this is to get the Ext.dom.Element instead of the actual DOM node. This will allow you to use .on(). This is done by using Ext.get() instead of Ext.getDom().
var elDom = Ext.get('some_id');
if(elDom) {
elDom.on('click', function() {
Ext.Msg.alert('Status', 'Already get the element from the dom');
});
}

Related

Polymer - can not click event outside of element to close itself

Polymer 1.*
I had to write my own dropdown menu. I need to close the menu when the user clicks outside of the element. However, I am not able to catch the event when a user clicks outside of the element so I can close the menu.
Any ideas what I am doing wrong?
EDIT: I've studying paper-menu-button which closes paper-listbox when I click outside the element.... but I don't see anywhere where it catches that event https://github.com/PolymerElements/paper-menu-button/blob/master/paper-menu-button.js#L311
<dom-module id="sp-referrals-reservations-dropdown">
<template>
<style include="grid-dropdown-styles">
</style>
<div id="dropdown" class="grid-dropdown">
<paper-listbox>
<div class="grid-dropdown-item">Convert to stay</div>
<div class="grid-dropdown-item">Cancel reservation</div>
<div class="grid-dropdown-item">Delete reservation</div>
</paper-listbox>
</div>
</template>
<script>
(function() {
'use strict';
Polymer({
is: 'sp-referrals-reservations-dropdown',
behaviors: [Polymer.IronControlState],
properties: {
},
listeners: {
'tap': '_close',
'click': '_close',
'blur': '_close',
'focusout': '_close',
'focusChanged': '_close',
'focus-changed': '_close',
'active-changed': '_close',
'activeChanged': '_close',
'iron-activate': '_close',
'ironActivate': '_close',
},
open: function(e) {
},
_close: function() {
console.log('aaa');
this.$.dropdown.style.display = "none";
},
});
})();
</script>
</dom-module>
I am not sure, will it be enough, but if you wrap the sp-referrals-reservations-dropdown element with a parent-element then you can listen to parent-element events same as its child.
<parent-element></parent-element>
<dom-module id="parent-element">
<template>
<style>
:host {
display:block;
background:green;
width:100%;
height:100vh; }
</style>
<sp-referrals-reservations-dropdown id="spref"></sp-referrals-reservations-dropdown>
At parent's script:
Polymer({is:'parent-element', properties:{},
listeners:{ 'tap': '_taped'},
_taped:function(t){
this.$.spref._close();
}
});
this _taped functions will call child's _close function. Hope its help.
Incase of needed more. We can develop this.
Demo
EDIT
Wrap your element into paper-dialog. And at ready:function() call
this.$.dialog.open()
Then when you click outside of the element. paper-dialog will close automatically.
Just FYI, you weren't able to get this to work because custom elements don't listen for events outside of their own encapsulation unless you explicitly wire them up to do so... and if you do so, you can't use Polymer's built-in event handling.
So something like this would work:
// Insert this somewhere it'll get run once attached to the DOM
// This line keeps clicks within your element from closing the dropdown
this.shadowroot.addEventListener('click', (event) => { event.stopPropagation(); });
// And this listens for any click events that made it up to body, and closes the element
document.querySelector('body').addEventListener('click', this._close);
Or, at least, that's what I think was going on. The polymer elements either did it by binding to a different event (blur?) or by having the parent element trigger an event on click that told the child element to close.

Replace element with razor textarea

I want to take a tag and replace with a #Html.textarea() razor html helper but it doesn't look as if JQuery can replace DOM elements with html helpers. How do I go about this?
using(#Html.BeginForm())
{
<a id="clickme">Edit</a>
<div>#Model.username</div>
}
How can I replace this div with #Html.Textarea ? JQuery could do it with div and input tags.
jQuery cannot replace a tag with #Html.TextArea() !
The TextArea helper method is a C# method, which gets executed when razor tries to render the view. This happens in your web server. jQuery is a client side library and anything you do with jQuery happens at client side, in your browser.
But all these helper methods ultimately generate some HTML for DOM elements. That means, you can use jQuery to manipulate visibility of that.
If you are trying to do something like an inline edit, you can use a script like this , to start with
First, render the text area along with your label div, but have it hidden initially. Also wrap the label,edit link and the hidden input inside a container div which we can use later to help with our jQuery selectors.
#using (#Html.BeginForm())
{
<div class="edit-item">
Edit
<div class="edit-label">#Model.FirstName</div>
#Html.TextAreaFor(a => a.FirstName,
new { style = "display:none;", #class = "edit-text" })
</div>
<div class="edit-item">
Edit
<div class="edit-label">#Model.UserName</div>
#Html.TextAreaFor(a => a.UserName,
new { style = "display:none;", #class = "edit-text" })
</div>
}
Now when the user clicks edit, you have to toggle the visibility of the label and hidden input and update the value of label after user done editing the value in the input element.
$(function () {
$("a[data-mode]").click(function (e) {
e.preventDefault();
var _this = $(this);
var c = _this.closest(".edit-item");
c.find(".edit-text").toggle();
c.find(".edit-label").toggle();
if (_this.attr("data-mode") === 'label') {
_this.attr("data-mode", 'edit');
_this.text("done");
} else if (_this.data("mode") === 'edit') {
c.find(".edit-label").text(c.find(".edit-text").val());
_this.text("edit");
_this.attr("data-mode", 'label');
}
});
});
This is a head start. You can optimize this code as needed.
Here is a working jsfiddle for your reference

Hover not working on AJAX

I have the below content that loads on through AJAX.
<div class="grid">
<div class="thumb">
<img alt="AlbumIcon" src="some-image.jpg">
<div style="bottom:-75px;" class="meta">
<p class="title">Title</p>
<p class="genre"> <i class="icon-film icon-white"></i>
Genre
</p>
</div>
</div>
</div>
Additionally, I have writen the following script in jquery that applies to the above 'div.grid'.
jQuery(function ($) {
$(document).ready(function () {
$(".grid").on({
mouseenter : function () {
$(this).find('.meta').stop().animate({
bottom:'0px'
},200);
},
mouseleave : function () {
$(this).find('.meta').stop().animate({
bottom:'-75px'
},200);
}
});
});
});
The script works fine when the page loads the first time. However, the hover effect doesn't work once the above div is generated via AJAX after clicking on an 'a' tag. I can't seem to figure out what's wrong here? New to all this. Can anyone help?
To append these event handlers to dynamically generated elements, you need to bind to the document or another static parent element and then specify .grid as the second argument passed to .on.
The second argument is used as a filter to determine the selected elements that trigger the event. So when the event is fired it will propagate to the document or parent element selected by jquery. The event target will then be scrutinized using the selector provided as the second argument. If the target matches the second argument, (.grid in our case), the event is fired.
You can read more in the jQuery documentation.
Also, since your using document.ready there is no need for the short hand ready statement, jquery(function($).
$(document).ready(function () {
$(document).on({
mouseenter : function () {
$(this).find('.meta').stop().animate({
bottom:'0px'
},200);
},
mouseleave : function () {
$(this).find('.meta').stop().animate({
bottom:'-75px'
},200);
}
}, ".grid");
});
you lost your binding because of ajax that overwrite your div with class=".grid"
use parent element for binding
$('.ParentElementClass').on("mouseleave", ".grid", function(){...})
more from jquery api
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
Not sure what you're shooting for here but a little malformed HTML may have done it...
jsFiddle Demo
<div class="grid">
<div class="thumb">
<img alt="AlbumIcon" src="some-image.jpg" />
<div style="bottom:-75px;" class="meta">
<p class="title">Title</p>
<p class="genre"><i class="icon-film icon-white"></i>Genre</p>
</div>
</div>
</div>
$(function () {
$(".grid").on({
mouseenter: function () {
alert('entered');
$(this).find('.meta').stop().animate({
bottom: '0px'
}, 200);
},
mouseleave: function () {
alert('left');
$(this).find('.meta').stop().animate({
bottom: '-75px'
}, 200);
}
}, ".thumb");
});
});
Be sure to close img tags. They're notorious for causing intermittent glitches.
You can just use the hover function:
jQuery(function ($) {
$(document).ready(function () {
$(".grid").hover(function () { /*mouseenter*/
$(this).find('.meta').stop().animate({
bottom:'0px'
},200);
},function(){ /*mouseleave*/
$(this).find('.meta').stop().animate({
bottom:'-75px'
},200);
}
});
});
Explanation:
The first parameter function does the work of mouseenter and the second does the work of mouseleave.
I'd recommend using those both, mouseenter and mouseleave in situation when you don't want an effect back when the user gets off his mouse from the element.

jQuery Radio Button Image Swap

I am essentially brand new to coding (html5 forms, CSS3 and now jQuery).
What I am trying to do is have an imageswap (which I have done) attached to a radio button. So what I'm doing is replacing the buttons with images, each with a "pressed" version. However, before even attaching it to a form function/radio button input, I want to find a way so that when I click one button, it switches the other images back to "un-pressed". Essentially so that only one image can be "pressed" at a time.
Right now the code for me pressed images are
$(function() {
$(".img-swap1").live('click', function() {
if ($(this).attr("class") == "img-swap1") {
this.src = this.src.replace("_U", "_C");
} else {
this.src = this.src.replace("_C","_U");
}
$(this).toggleClass("on");
});
});
I thought about using an if statement to revert all the "_C" (clicked) back to "_U" (unclicked).
Hopefully I've included enough information.
A good pattern for solving this problem is to apply the unclicked state to ALL your elements, then immediately afterward apply the clicked state to the targeted element.
Also, your if statement ($(this).attr("class") == "img-swap1") is redundant -- it will always be true because it's the same as the original selector $(".img-swap1").live('click'...
Try
$(function() {
$(".img-swap1").live('click', function() {
$(".img-swap1").removeClass('on').each(function(){
this.src = this.src.replace("_U", "_C");
});
this.src = this.src.replace("_C","_U");
$(this).addClass("on");
});
});
If I understand the question correctly the following may work for you:
$(function(){
$('.img-swap1').live('click', function() {
$('.img-swap1').removeClass('on').each(function(){
$(this).attr('src', $(this).attr('src').replace("_C", "_U")); // reset all radios
});
$(this).attr('src', $(this).attr('scr').replace("_U", "_C")); // display pressed version for clicked radio
$(this).toggleClass("on");
});
});
I hope this helps.

How to reference classes in an iframe

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