Dijit ComboButton / DropDownMenu onclick misunderstanding - javascript

I've just begun to play around with Dojo. I simply wanted to display a dialog when an item in a Dijit ComboButton's DropDownMenu is clicked. I tried using dojo.connect to associate the onclick event with a function which would simply display a dialog with the text contained in the item, with no luck.
I've managed to get it working in a horrible way. All the work is now actually written to the onclick attribute manually. I'm clearly misunderstanding something here. This is what I currently have:
JS:
require(["dijit/form/Button", "dijit/form/FilteringSelect", "dijit/DropDownMenu", "dijit/MenuItem"]);
//if the following is defined inside dojo.ready, nothing happens
function getmail(text)
{
alert('No mail from '+text);
}
dojo.ready(function(){
//the following does nothing:
dojo.connect(dojo.query(".dijitMenuItemLabel"), "onclick", function(evt) {
console.log("mail item clicked");
alert('Blah');
//dojo.stopEvent(evt);
});
});
HTML:
<form method="POST">
<div data-dojo-type="dijit.form.ComboButton" id="getmail">
<span>Get All Mail</span>
<div data-dojo-type="dijit.DropDownMenu">
<div data-dojo-type="dijit.MenuItem"
data-dojo-props="onClick:function(){getmail(dojo.trim(dojo.query('.dijitMenuItemLabel', this.domNode)[0].innerHTML))}">
Yahoo</div>
<div data-dojo-type="dijit.MenuItem">Google</div>
</div>
</div>
</form>
What does it look like I am clearly misunderstanding about Dojo?
(Or maybe I'm making simple JavaScript mistakes)
JSFiddle

You should be able to do it with something like
var myButton = dijit.byId('getmail');
myButton.on('click', function(){ alert('clicked') });
My guess is that you confused dojo.byId and dijit.byId when you fetched your button - regular DOM nodes work when you conenct a lowercase 'onclick' but widgets fire a camel case 'onClick' event (the distinction is because dijits fire with some keyboard events, for accessibility).
However, for newer versions of Dojo it is probably best to stay away from dojo.connect and instead just use simpler ".on" API I showed.
Ah, and before I forget, it also looks like you could have forgotten to run the Dojo parser (or set parseOnLoad to true) so the button was never created. Can you provide a fully executable example on JSFiddle?

Related

Identify HTML elements when event triggers

I have my app with tons of buttons/inputs/etc. with different events. I want to clearly identify each one of them which some event triggers on.
For example, when I have a piece of my app:
<div class="someClass">
<div>
<someOtherElement>
<div></div>
<div><button ng-click="someClickEvent($event)"></button></div>
</someOtherElement>
</div>
</div>
I want to identify somehow, which button I have just clicked:
function someClickEvent(e) {
// some identification code here
}
[edit]
Maybe I wrote this wrong... I want some identification like XPath or something that will point which button were triggered (for error logging purposes).
So when I click my button and some error occurs, I want to identify the button and log some information about it (e.g. div[0].someClass>div[0]>someOtherElement[0]>div[1]>button[0]).
You can get identify the button and log it by this:
$scope.clickFunc = function(event){
$scope.clickedElement = event.target.outerHTML;
};
DEMO: http://jsfiddle.net/rjdzuxaL/1/
Use ng-click instead on onclick
<button ng-click="myFunction($event)">test</button>
Working demo
Change HTML to:
<button ng-click="myFunction($event)">test</button> //onclick works on javascript. For Angularjs, use ng-click.
JS:
$scope.someClickEvent = function(e) {
// some identification code here
var element = e.target; // this will give you the reference to the element.
}
You should avoid handling DOM in the controller. Use directives for them.

Preventing event bubbling (for javascript onclick events)

I am using javascript to interact with a CMS which provides a button for users to add things to their basket.
However, I am using the javascript to try and prevent the customer from doing so unless they have made a selection from a drop-down menu elsewhere on the page.
As there are many different buttons that could potentially get them to the basket (including the example below) and all of which have different methods for doing so, rather than write many lines of code to prevent each method and then re-enable that method when a selection is made I am trying to do a kind of 'catch-all' fix where I just cover any such buttons / links with another div so as to effectively 'mask' the button below it until they make a decision.
I first tried to use absolute positioned divs to do this which works beautifully until the user does something like re-size a textbox on the page and then suddenly my absolutely positioned div is in the wrong place!!
So I'm now using JQuery's .wrap() which solves this problem nicely.. BUT.. Now I can't use z-index to position the div above the required buttons as those buttons are within the mask not below it!
I have done a lot of reading about event bubbling but I am not sure whether I've not found the right information yet, or maybe I understand it correctly or possibly that event bubbling is leading me down the wrong path all together as I can't seem to take those concepts and apply them to this scenario.
so.....
given the following HTML structure:
<div class="btnMask">
<div class="button">
<a onclick="pageSubmit();return false;" href="#" id="addToBasket">
<span>Add to Basket</span>
</a>
</div>
</div>
where the div with class="btnMask" is added by my javascript.
Plus the following JQuery:
$('.btnMask').click(function() {
// prevent default actions and alert the customer to select something;
});
How do I go about stopping the tag firing when clicking the .btnMask div?
and (in case the answer to that does not make the answer to my other question obvious...)
How would I switch that on and off ? (I have a function that checks the drop-down onchange and sets the z-index to 99 / -99 so I would want to change this to incorporate this new method.)
Thank you in advance for your help.
<< EDIT >>
Using the initial answers to this I managed to solve the problems for links that take you away from the page using a regular href.
So I have now fixed the links where the HTML is like the following:
<div class="btnMask">
<div class="button">
<a id="nextPage" href="/link/toanotherpage.asp?id=667868465726122926234">
<span>Click to go to Page 2</span>
</a>
</div>
</div>
However, like I said there are many methods being used to take people away from the page and and e.preventDefault(); and e.stopPropagation(); don't work for my original example (presumably because they use an onclick rather than a href ?).
Is there a way to do the same thing as e.preventDefault(); and e.stopPropagation(); are doing on my .btnMask div but will also deal with contained links that are being trigged by an onclick?
thanks
<< EDIT >>
Updated the question title to reflect the exact issue rather than just event bubbling on regular links.
If you want to prevent event bubbling and cancel default action then you can return false from the event handler.
$('.btnMask').click(function() {
return false;
});
Or use preventDefault and stopPropagation
$('.btnMask').click(function(e) {
e.preventDefault();
e.stopPropagation();
});
$('.btnMask').click(function(e) {
e.stopPropagation();
});
Your onclick handler is fired before your jquery click handler. You can do something like this
function pageSubmit() {
alert('pageSubmit');
}
var link = document.getElementById('addToBasket');
var linkClickHandler = link.onclick;
link.onclick = null;
$('.button').data('linkClickHandler', linkClickHandler);
$('.button').on('click', function(e){
var clickHandler = $(this).data('linkClickHandler');
var link = $(this).find('a').get(0);
clickHandler.apply(link, [e]);
});
$('.btnMask').on('click', function(e){
if (!$(this).hasClass('test')) {
e.preventDefault();
e.stopPropagation();
}
});
and the html as
<div class="button">
<a onclick="pageSubmit();return false;" href="#" id="addToBasket">
<div class="btnMask test">
<span>Add to Basket</span>
</div>
</a>
</div>
If you remove the class test from btnMask div the pageSubmit handler will not be called,
and when it is present the handler is called.

Basic jQuery Issues on IE9 (Toggle)

I'm not really a developper. I prefer to design my websites ... So, for my actual project, i must developping some "basic" scripts.
I've met a problem with this:
<script type="text/javascript">
$("button").click(function toggleDiv(divId) {
$("#"+divId).toggle();
});
;
</script>
Into Head-/Head
LINK
<div> id="myContent">Lorem Ipsum</div>
It works for IE8. (Miracle). But not the others browsers...
The idea is that when u click on "LINK" a windows appears and when you click again, the window close.
Any idea ?
Thanks for u time !
One of the problems is you're mixing two different styles of binding event handlers: one of them is good (the jQuery method), the other is bad (the javascript: protocol in your href attribute) - the two don't work together in any way. Another problem is that your selector is completely incorrect (it's looking for a button) for the HTML you've provided (you never create a button).
I'd suggest using a HTML5 data-* attribute to specify the id for the <div> on your <a> element:
LINK
<div id="mycontent">Lorem ipsum</div>
Then use the following jQuery code:
$('a').click(function(e) {
e.preventDefault(); // e refers to the event (the click),
// calling preventDefault() will stop you following the link
var divId = $(this).data('divid');
$('#' + divId).toggle();
});
Note that I've used this in the above code; what this refers to depends on the context in which you use it, but in the context of a jQuery event handler callback function, it will always refer to the element that triggered the event (in this case, your <a> element).
If you extract toggleDiv from the handler, it ought to work. You will probably also need to return false to keep the href from trying to go anywhere.
<script type="text/javascript">
function toggleDiv(divId) {
$("#"+divId).toggle();
return false;
}
</script>

javascript de-anonymizing a click function

really basic stuff here. I'd like to give a click function a name and assign some parameters to it. The goal is code reusability such that I can write only one generic function for common tasks such as for enabling users to delete various data.
Here's a jsfiddle to show you what I mean.
And here's that code:
the HTML:
<button>delete this</button>
<div data-id="3" class="delete">something bad</div>
<div data-id="4" class="delete">something else bad</div>
and the JS:
// this function would be loaded on my site's template and therefore would be available across my entire site.
function deleteThis(data_id){
$('button').on('click', 'button', function(){
$('div[data-id="'+data_id+'"]').hide();
});
}
var clicked_id=3;
function deleteThis(clicked_id);
// this function would be called on the various pages where users can delete things and this variable, clicked_id, would be assigned=3 by the user's action on that page.
How do I give this button click event a name?
update thanks all! the $('button') should have been $(document.body) or the button's parent element. It works if you make that simple change. You can also do it as Michael Buen suggests below.
Just refactor your code, put the delete functionality on its own function
<button>delete this</button>
<div data-id="3" class="delete">something bad</div>
<div data-id="4" class="delete">something else bad</div>
​
$('button').on('click', function() { deleteImmediately(3) });
function deleteImmediately(id) { -- refactored code
$('div[data-id='+id+']').hide();
}​
Live test: http://jsfiddle.net/e2kuj/2/
In your fiddler, the (function deleteThis(){})() is making it private and you are trying to access it as a global!
I think you're misunderstanding events. deleteThis only makes sense if it's in the handler.
corrected HTML: (don't use custom attributes for referencing HTML - They're slower)
<button>delete this</button>
<div id="del_3" class="delete">something bad</div>
<div id="del_4" class="delete">something else bad</div>
JS: (untested)
var deleteTargetId = 'del_3'; //clicked_id renamed for clarity
function deleteThis(targetId){
$('#'+targetId).remove(); //removes rather than hides the html
}
$('button').click( function(){
deleteThis(deleteTargetId);
} );
Now you could swap deleteTarget and the HTML with that ID would get yoinked.
However, if this is homework, I'm wondering if you understand the assignment. The var named 'clicked_id' suggests the idea is to click the divs to make them disappear and use delegation. That one's easy.
You'll need to understand event delegation and event bubbling to see what's going on here. Basically when something is clicked, the event then fires on the parent element and then that parent element's parent element, all the way up to the HTML tag. This happens with all events and doesn't cause the trouble you might think because containers are rarely assigned listeners for events. Links and buttons are more typically end point nodes or at most contain a span or an image. Usually when bubbling causes a problem it's because somebody's doing something awful with HTML or they should've been using delegation in the first place.
'on' is the new piss-poor name for the once appropriately named and less confusion-prone 'delegate' jquery method. Essentially anything in the body with the class 'delete' triggers the handler. We don't care about the ID since the idea is to kill the div that was clicked and 'this' gives us a reference to it. This is unusual behavior for JQ, since most methods would have 'this' point at the 'body' but it's obviously a more useful thing to point at for event delegation.
$('body').on('click', '.delete', function(e){
$(this).remove(); //this refers to the originally clicked element
} );
//note: not the solution you asked for, but possibly the one you needed.
It was almost right. I updated it -> http://jsfiddle.net/fz5ZT/41/
function deleteThis(id){
$('button').click(function(){
$('div[data-id="'+id+'"]').hide();
});
};
deleteThis(3);​
you can remove the element in a different way:
$('button').on('click', function(){
$(this).next("div").remove();
});
http://jsfiddle.net/fz5ZT/46/
You could just use $('button').on('click', 'button', clickHandler); to reference the clickHandler function.
I am big fan of such things since apart from being reusable it has the following advantages.
I will be able to just send across a patch in case there's a bug in the clickHandler
Someone can augment my method which is not possible with anonymous methods
Readable, and also useful to see the stack trace in case of errors
Hope that helps.
Update:
function clickHandler(ev) {
ev.preventDefault();
// ... handler code
}

call javascript function on hyperlink click

I am dynamically creating a hyperlink in the c# code behind file of ASP.NET. I need to call a JavaScript function on client click. how do i accomplish this?
Neater still, instead of the typical href="#" or href="javascript:void" or href="whatever", I think this makes much more sense:
var el = document.getElementById('foo');
el.onclick = showFoo;
function showFoo() {
alert('I am foo!');
return false;
}
Show me some foo
If Javascript fails, there is some feedback. Furthermore, erratic behavior (page jumping in the case of href="#", visiting the same page in the case of href="") is eliminated.
The simplest answer of all is...
My link
Or to answer the question of calling a javascript function:
<script type="text/javascript">
function myFunction(myMessage) {
alert(myMessage);
}
</script>
My link
With the onclick parameter...
<a href='http://www.google.com' onclick='myJavaScriptFunction();'>mylink</a>
The JQuery answer. Since JavaScript was invented in order to develop JQuery, I am giving you an example in JQuery doing this:
<div class="menu">
Example
Foobar.com
</div>
<script>
jQuery( 'div.menu a' )
.click(function() {
do_the_click( this.href );
return false;
});
// play the funky music white boy
function do_the_click( url )
{
alert( url );
}
</script>
I prefer using the onclick method rather than the href for javascript hyperlinks. And always use alerts to determine what value do you have.
<a href='#' onclick='jsFunction();alert('it works!');'>Link</a>
It could be also used on input tags eg.
<input type='button' value='Submit' onclick='jsFunction();alert('it works!');'>
Ideally I would avoid generating links in you code behind altogether as your code will need recompiling every time you want to make a change to the 'markup' of each of those links. If you have to do it I would not embed your javascript 'calls' inside your HTML, it's a bad practice altogether, your markup should describe your document not what it does, thats the job of your javascript.
Use an approach where you have a specific id for each element (or class if its common functionality) and then use Progressive Enhancement to add the event handler(s), something like:
[c# example only probably not the way you're writing out your js]
Response.Write("My Link");
[Javascript]
document.getElementById('uxAncMyLink').onclick = function(e){
// do some stuff here
return false;
}
That way your code won't break for users with JS disabled and it will have a clear seperation of concerns.
Hope that is of use.
Use the onclick HTML attribute.
The onclick event handler captures a
click event from the users’ mouse
button on the element to which the
onclick attribute is applied. This
action usually results in a call to a
script method such as a JavaScript
function [...]
I would generally recommend using element.attachEvent (IE) or element.addEventListener (other browsers) over setting the onclick event directly as the latter will replace any existing event handlers for that element.
attachEvent / addEventListening allow multiple event handlers to be created.
If you do not wait for the page to be loaded you will not be able to select the element by id. This solution should work for anyone having trouble getting the code to execute
<script type="text/javascript">
window.onload = function() {
document.getElementById("delete").onclick = function() {myFunction()};
function myFunction() {
//your code goes here
alert('Alert message here');
}
};
</script>
<a href='#' id='delete'>Delete Document</a>

Categories