from plain javascript to dojo framework - javascript

I've started to learn the dojo Toolkit and i like it so far, it seems to me easier to understand than jquery/prototype JS. I'm still new at it (and in javascript) and while there is a plethora of docs available on the net i don't really understand how to achieve simple tasks like making a hidden visible with dojo. So to the problem:
the html
<!-- the numder in id="comment" and in href="javascript:display_comments('')" is the post_id that i want the comments to be fetched for -->
<div class="comments">
<a id="comment8" href="javascript:display_comments('8');">comments</a>(21)
</div>
<div style="visibility: hidden;" id="display_comments8">
</div>
<div class="comments">
<a id="comment7" href="javascript:display_comments('7');">comments</a>(13)
</div>
<div style="visibility: hidden;" id="display_comments7">
</div>
<div class="comments">
<a id="comment15" href="javascript:display_comments('15');">comments</a>(20)
</div>
<div style="visibility: hidden;" id="display_comments8">
</div>
the javascript
function display_comments(id) {
divid = 'display_comments'+id;
var element = document.getElementById(divid);
if(element.style.visibility == 'hidden') {
element.style.visibility='visible'
}else if(element.style.visibility == 'visible') {
element.style.visibility='hidden';
element.innerHTML='';
}
}
The parameter for display_comments() in the post_id which then is merged with the words 'display_comments' so to know which div to make visible. How can this be achieved in dojo?

Basically what you want to do here is automate things a bit right? If you attribute your links either by id, like i use below, or some other way (non validatable properties or html5 data-attributes) then you can use dojo.query to find all the nodes in your container and attach an event to them. I gave you a link to the dojo.query syntax page in case you wanted to make your query syntax more specific.
After looping through all the a nodes in container and attaching a click event with a handler that passes the node's id (the dojo.partial stuff), you just need to handle the click event. The toggle display uses dojo core to change and modify the style of the node - pretty simple.
Based on your example this is how I would change your code.
There are a lot of ways you could achieve these results. Personally, I would create templated widgets. Since this code looks repetitive, you could dojo.declare a comment class and dojoattachevents to the links and dojoattachpoint to the hidden node. This way you wouldn't have to dojo.query or dojo.byId since widget would wire all that up for you. You could create one for each and use class syntax to handle the logic.
<div id="container">
<div class="comments">
<a id="8">comments</a>(21)
</div>
<div style="visibility: hidden;" id="display_comments8">
</div>
<div class="comments">
<a id="7">comments</a>(13)
</div>
<div style="visibility: hidden;" id="display_comments7">
<div>
dojo.query reference
dojo.query("#container a").forEach(function(node) {
dojo.connect reference
dojo.partial reference
dojo.connect(node, 'onclick', dojo.partial(toggleDisplay, node.id));
});
dojo.byId reference
dojo.style reference
function toggleDisplay(node) {
var hiddenNode = dojo.byId('display_comments' + node);
var display = dojo.style(hiddenNode).visibility === 'visible' ? 'hidden' : 'visible';
dojo.style(hiddenNode, {
visibility: display
});
}
Working Example
jsfiddle example
Books
we have dojo the definitive guide and mastering dojo and getting startED with dojo.
PS all these books are outdated and the best information is found on the test pages/the irc #dojo chat room/and the reference guides.

Related

Fastest way to template and append elements from array

Using jQuery and Javascript, I am building a chatbox from an array of messages. My current setup is something similar to this:
HTML:
<div id="messageTemplate">
<div class="messageContainer">
<div class="chatMessage"></div>
<div class="chatTime"></div>
<div class="chatActions">
<span class="chatAction deleteMessage">Delete</span>
</div>
</div>
</div>
Javascript:
var template=$('#messageTemplate');
var chatbox=$('#chatbox');
$.each(messageArr,function(index,messageObject) {
var newMessage=$(template.html()); //Make a new DOM
newMessage.find('div.chatMessage').text(messageObject.message);
newMessage.find('div.chatTime').text(messageObject.time);
newMessage.find('div.chatAction.deleteMessage').click(function() {
//Delete message Code
});
//Append newMessage to chatbox
newMessage.appendTo(chatbox);
});
This code works, but after reading this article I found out this is not efficient at all. With 100+ chat messages this starts to slow down.
What's the best way to be doing this? Not looking for code to be written for me, but just a general guide on the best method to template, build the html, append, and add click handlers?

Javascript / Greasemonkey / Userscript.js identify element and remove one of many classes

I've spent far too many hours trying to figure this out and as JavaScript is not my primary language and not yet a jQuery guru I've determined I need to ask for help.
In a case where a generated page has a structure where it has a DIV for some odd reason no ID, multiple non-standard data tag attribute tags, but at least standard style CLASS assignment....however...it has been assigned MULTIPLE classes.
Now, just one of those style classes is such that it has a code event associated that I want to neuter and leave all other classes still assigned. What I've tried there (this list is far from complete I have tried many things):
document.getElementsByClassName('Goodclass01')[0].remove('BADCLASS');
document.querySelectorAll('[data-tag-one="["value",
"value"]"]').remove('BADCLASS');
Various jnode calls that all fail due to claims of being unknown
A couple variations of something referred to as the "location hack" none of
which I could get to work but may have very well have been user error.
Safewindow attempt to just replace BADCLASS javascript function all together
but not ideal explained below.
Here is an example of the kind of structure of the target:
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03 BADCLASS"
data-tag-one="["value", "value"]">
</div>
In this example there is a javascript function that fires upon clicking the href link above due to the function being associated with BADCLASS style assignment. So, from lots of searching it seemed like I should be able to grab that DIV by any of the initially assigned classes (since there is unfortunately not a class ID which would make it very easy) but then reassign the list of classes back minus the BADCLASS at page load time. So, by the time the user clicks the link, the BADCLASS has been removed to look like this:
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03"
data-tag-one="["value", "value"]">
</div>
I also read that simply using unsafewindow to replace the BADCLASS javascript function could be possible, so I am open to hearing one of you gurus help with how easy (or hard) that would be. In a case where BADCLASS could be shared function code perhaps called by another element on the page still having that initial class that perhaps we desire to continue to function which is why if it is only a single element that needs to be altered, I would rather just change this one href div.
Hope the explanation makes sense and what is probably a laughable simple example above for the Javascript gurus so forgive me but your help is greatly appreciated and will save more hair pulling! :)
EDIT: This must work above all in Chrome browser!
Remove the class from all elements
If you want to remove the class from all elements that have the class, simply select all of the elements with that class and remove the class from their class lists.
[...document.querySelectorAll('.BADCLASS')]
.forEach(e => e.classList.remove('BADCLASS'));
const elements = [...document.querySelectorAll('.BADCLASS')];
elements.forEach(e => e.classList.remove('BADCLASS'));
console.log(elements);
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03 BADCLASS"
data-tag-one='["value", "value"]'>link</a>
</div>
Using jQuery:
$('.BADCLASS').removeClass('BADCLASS');
const elements = $('.BADCLASS');
elements.removeClass('BADCLASS');
console.log(elements);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03 BADCLASS"
data-tag-one='["value", "value"]'>link</a>
</div>
Remove the class from a subset of elements
If you only want to remove the class from a subset elements, select those elements then from the class from their class lists.
[...document.querySelectorAll('.Goodclass01, .Goodclass02, .Goodclass03')]
.forEach(e => e.classList.remove('BADCLASS'));
const elements = [...document.querySelectorAll('.Goodclass01, .Goodclass02, .Goodclass03')];
elements.forEach(e => e.classList.remove('BADCLASS'));
console.log(elements);
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03 BADCLASS"
data-tag-one='["value", "value"]'>link</a>
link
</div>
Using jQuery:
$('.Goodclass01, .Goodclass02, .Goodclass03').removeClass('BADCLASS');
const elements = $('.Goodclass01, .Goodclass02, .Goodclass03');
elements.removeClass('BADCLASS');
console.log(elements);
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03 BADCLASS"
data-tag-one='["value", "value"]'>link</a>
link
</div>
Run at document idle
The default for the run-at directive is document-idle, but if for some reason that has been changed, either it needs to be document-idle, or you need to otherwise delay execution of the script until the document has loaded.
You could use the run-at directive in the userscript header like so:
// #run-at document-idle
Or attach a load event listener to the window
window.addEventListener('load', function() { /* do stuff */ }, false);
Include jQuery
If you're using one of the jQuery solutions, you will have to include jQuery using the require userscript header directive like so:
// #require https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
Got it with the help of both of the clear, awesome correct answers below that literally came in within seconds of each other and only a few min after my post, so thanks to both #Tiny and #Damian below!
I'm upvoting both as they both listed the same correct jQuery answers, and Tiny also provided the pure JS.
I am posting the full answer below because without the other steps, with Tamper/Greasemonkey neither will produce the desired results.
First, Tamper/Greasemonkey do not load jQuery by default, so it is just easy as add #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.mi‌​n.js to your current script and also put this.$ = this.jQuery = jQuery.noConflict(true); to avoid any versioning conflicts.
Also, in this case unfortunately I HAD to change my TamperMonkey header to:
// #run-at document-idle
along with the above mentioned:
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
and begin the script with:
this.$ = this.jQuery = jQuery.noConflict(true);
and finally the primary accepted/best answer in this case of:
$('.Goodclass01').removeClass('BADCLASS');
NOTE: The above #run-at line is required, and since so many (all) of my current Tamper/Greasemonkey scripts are actually set by default to run at START, this is of importance as it means functions like this must be separated to their own scripts to run instead AFTER the page loads (idle). Once this is added, even the above pure JS answer from Tiny did in fact produce the desired result.
As the simplest one-line answer that I was hoping was possible in Javascript, as it is so many other languages in a single line of code. I've used it in the past, but was not aware of this particular removeClass method.
Your question mentions jQuery. Did you want a solution in jQuery?
If so, it's as easy as:
$(".Goodclass01").removeClass("badclass");
Explanation:
jQuery can be referenced as jQuery() or $(). The parameters you can pass are: 1, a Selector statement (like CSS), and 2, context (optional; default is document).
By stating $(".Goodclass01") you are stating, "Give me a jQuery object with all elements that have the class Goodclass01." Then, by using the removeClass() function, you can either pass it no parameters and it would remove all classes, or you can pass it specific classes to remove. In this case, we call .removeClass("badclass") in order to remove the undesired class.
Now, if you need to select only specific elements, such as links that have Goodclass01, you can do:
$("a.GoodClass01").removeClass("badclass");
Or, if you want to select anything that has Goodclass01, but NOT Goodclass02, you can do:
$(".Goodclass01:not(.Goodclass02)").removeClass("badclass");
jQuery is not as intimidating as it looks. Give it a shot!
Edit: I also noticed you were trying to capture a link with maybe a specific property. You can use the [property] syntax to select elements that have a specific property. Most typically, people use $("a[href^=https]") or something to that effect to select all a tags with the property href that begins with ^= the string https.
You could, in your case, use the following...
$("a[data-tag-one]")
... to select all links that have the property data-tag-one.
Note: One thing to keep in mind is that, a jQuery object is different than a pure DOM element. If you have a collection of multiple elements and want to use a pure JavaScript function on one element in particular, you would have to reference it with either [0] or .get(0). Once you do that, you will no longer be able to use jQuery methods until you convert it back to a jQuery object.
But, since jQuery has a whole slew of methods to use to make DOM manipulation easier, you can probably accomplish what you need to using those methods.
Edit: I've included a snippet below so you can see some of the jQuery selectors in action.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
div#main * { background-color: #66ff66; }
div#main .BADCLASS, div#main .BADCLASS * { background-color: #ff8888 !important; }
</style>
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03 BADCLASS"
data-tag-one='["value", "value"]'>All classes and data-tag-one</a><br />
<a href="SOME LINK" class="Goodclass01 BADCLASS" data-tag-one='["value", "value"]'>Goodclass01 and data-tag-one</a><br />
All classes, no data-tag-one<br />
<a href="SOME LINK" class="BADCLASS" data-tag-one='["value", "value"]'>Just BADCLASS and data-tag-one</a><br />
<br />
<table class="Goodclass01 BADCLASS"><tr><td>Here is a table</td></tr><tr><td>with Goodclass01 and BADCLASS</td></tr></table>
</div>
<hr>
<div id="buttons">
$(".Goodclass01").removeClass("BADCLASS");<br />
$("a.Goodclass01").removeClass("BADCLASS");<br />
$(".Goodclass01:not(.Goodclass02)").removeClass("BADCLASS");<br />
$("a[data-tag-one]").removeClass("BADCLASS");<br />
Reset the HTML<br />
</div>
<script>
$("#button1").click(function(){
$(".Goodclass01").removeClass("BADCLASS");
});
$("#button2").click(function(){
$("a.Goodclass01").removeClass("BADCLASS");
});
$("#button3").click(function(){
$(".Goodclass01:not(.Goodclass02)").removeClass("BADCLASS");
});
$("#button4").click(function(){
$("a[data-tag-one]").removeClass("BADCLASS");
});
$("#button5").click(function(){
var str = '<div class="main_content" data-tag-id="12345">Some stuff sits above</div>All classes, no data-tag-one<br /><a href="SOME LINK" class="BADCLASS" data-tag-one=\'["value", "value"]\'>Just BADCLASS and data-tag-one</a><br /><br /><table class="Goodclass01 BADCLASS"><tr><td>Here is a table</td></tr><tr><td>with Goodclass01 and BADCLASS</td></tr></table>';
$("div#main").html(str);
});
</script>

Get <div> elements without id in GWT

If i have html like this.Is there a way get a text apple between < div class="a" > and send it trought ajax to gwt application ?
<div class="A">
<div class="B">
<img class="icon" src="/images/ico.png" alt="" />
<div class="a">apple</div>
<div class="b">bannana</div>
</div>
</div>
and i have JavaScript like this :
$function(){
$('.B .icon').click(function(){
$(this).closest('.B').addClass('marked');
});
}
I would add this as a comment if I had enough reputation as I'm confused about your structure and question in general. Apologies if I don't understand correctly, but if you're typically traversing back up the DOM structure to the parent in your case could you use find to grab the element? .html() will grab the current content of said element.
$(function() {
$('.icon').click(function(){
var html = $(this).closest('.B').find('div.a').html();
// Do what you want with the contents. Simple alert as example.
alert(html);
});
});
This should get you what you're looking for. Please mark it as the answer if you find it matches what you need.
I'd suggest using .parent() rather than .closest('.B') if your elements will always be in the order you've posted and if further searching of the ancestor elements isn't needed.

JQuery find element in script

I am really not great at web stuff, so I am apologizing in advance for a potentially poor explanation of my problem.
Basically, I have a webpage which utilizes the handlebars js templating. Unfortunately, this means that many of my div elements are contained within javascript tags like the following:
<script type="text/x-handlebars" data-template-name="index">
<div class="row intro">
......
</div>
<div class="descript">
.....
</div>
</script>
My intent is to grab one of these div elements using jquery.find(), but from what I understand, the html within the script tags is not treated as part of the dom...so jquery does not see it as a dom element. I was wondering if there is any other way I could go about this. Some more code is included.
Here is another more explicit explanation in case the one I gave above was a little muddled: I am working on a personal website and would like to embed a project I have been working on in unity3d, but I need to add/remove elements based on whether or not the client has the unity3d web player installed. Normally I would get a particular element with
var $missingScreen = jQuery("#unityPlayer").find(".missing");
where 'missing' is simply an element inside unityPlayer which displays a link if the client does not have unity3d. I am also using some javascript templating to make my site look pretty and as a result, I have this problem:
<script type="text/x-handlebars" data-template-name="index">
<div class="row intro">
<div class="intro-text">Hi, I'm *****</div>
</div>
<div class="descript">
<p>
Here's a Project I have been working on in case I am of interest to you:
</p>
</div>
<div class="content">
<div id="unityPlayer">
<div class="missing">
<a href="http://unity3d.com/webplayer/" title="Unity Web Player. Install now!">
<img alt="Unity Web Player. Install now!" src="http://webplayer.unity3d.com/installation/getunity.png" width="193" height="63" />
</a>
</div>
</div>
</div>
<p class="footer">« created with Unity »</p>
</script>
Jquery cannot access the missing element. Is there any way to do this? Thanks for any help you can give me and sorry again for my inexperience.
EDIT* some people might want to know: here is how I determine whether or not to show the missing div. Another note; everything works fine if I remove the script tags...it is only when I put html within the script tags that it becomes inaccessible to jquery.
jQuery(function() {
var $missingScreen = jQuery("#unityPlayer").find(".missing");
$missingScreen.hide();
u.observeProgress(function (progress) {
switch(progress.pluginStatus) {
case "missing":
$missingScreen.find("a").click(function (e) {
e.stopPropagation();
e.preventDefault();
u.installPlugin();
return false;
});
$missingScreen.show();
break;
case "installed":
$missingScreen.remove();
break;
case "first":
break;
}
});
u.initPlugin(jQuery("#unityPlayer")[0], "temmp.unity3d");
});
Instead of
var $missingScreen = jQuery("#unityPlayer").find(".missing");
I would try out
var $missingScreen = jQuery("#unityPlayer").children(".missing");
or
var $missingScreen = jQuery("#unityPlayer .missing");
Don't forget the space between Player and .missing!
I hope it works.

jQuery click function affecting multiple divs

I'm trying to use jQuery's click function to apply a hover state to a selected div, without differentiating the div's in the JavaScript. I'm currently using:
$(document).ready(function(){
$(".project").click(function() {
$("a.expand").removeClass("hovered");
$("a.expand").addClass("hovered");
$(".project_full").hide();
var selected_tab = $(this).find("a").attr("href");
$(selected_tab).fadeIn();
return false;
});
With the HTML:
<div class="project first project_gizmoscoop">
<div class="title">
GizmoScoop!
<div class="date">2012</div>
</div>
<a class="expand" title="(Caption)" href="#project_1">GizmoScoop!</a>
</div>
<div class="project project_sc">
<div class="title">
Striking Code
<div class="date">2011</div>
</div>
<a class="expand" title="(Caption)" href="#project_2">Striking Code</a>
</div>
The .hovered class is applied to the clicked link (specific styles from an external CSS file). However, everything is being chosen. (See http://www.codeisdna.com for an example).
I know what I'm doing wrong (I should be specifying the individual ID's or using HTML5 data attributes), but I'm stuck unnecessarily. I feel like a complete newb right now, that I can't do something this simple (although I've done more advanced stuff).
You simply need to take advantage of jQuery's flexibility (and good programming practice) and reduce your scope accordingly. You're already doing something similar with your variable definition. For example, to target only those a.expand elements inside the instance of .project that's clicked:
$(".project").click(function() {
$(this).find("a.expand").removeClass("hovered");
...
});
$(".expand").click(function() {
$(this).addClass("hovered");
..
});

Categories

Resources