Skip navigation
All Places > Canvas Developers > Blog > 2018 > July
2018

I've been working on an easier way for teachers to upload Quiz Items and Outcomes from a Google Sheet. The template sheet uses Google Apps Script and a user's personal API key to interact with their courses.

 

Quizzes

Teachers frequently write tests and quizzes together. This mechanism allows teachers to write and upload dozens of questions easily from a Google Sheet.

Screenshot of the template spreadsheet

The Canvas API only allows questions to be uploaded to an existing Quiz resource. Teachers can select the appropriate course and quiz dynamically using the popup.

 

Quiz uploader sidebar with dynamic course and quiz selection boxesOnce a quiz resource has been selected, users can define the number of items to upload. The spreadsheet marks an item as successful and updates the next row to be uploaded so questions are not duplicated on subsequent runs.

Considerations

  • All questions uploaded are stored in the "Unnamed bank" question bank.
  • The "Topic" and "Primary Standard Indicator" fields are used to title questions for easy bulk sorting in the Canvas UI.

Updates to come

  • Error messages are...opaque. Often a failure results in "the resource does not exist," meaning the user hasn't selected a course or quiz.
  • Questions are not batched right now, so uploading too many questions can lead to a script timeout.

 

Outcomes

The Outcomes API is difficult to use. I know there are CSV imports now, but it is sometimes helpful to upload Outcomes as they're written rather than generating a CSV over and over.

 

Outcomes have to go into an Outcome Group. If there are no groups defined in the course, the course name is used as a top-level group.

 

The template spreadsheet is similar to the quiz template, with specific fields being defined for the upload to run successfully. There is a helper sheet where users can define different rubric scoring ranges for each upload.

Outcome upload template in a Google Sheet

Rubric template for uploading Outcomes

The Outcome upload sidebar is similar to the Quiz Item sidebar. Because new outcomes must be attached to a group, a dynamic list of codes and group titles are generated when the user selects their course.

Outcome group codes displayed dynamically on course selection

 

Considerations

  • Outcome uploads are done to the course, not to the user's account. This allows them to bulk-modify outcomes semester to semester as they update their courses.

 

Updates to come

  • Improve error messaging
  • Pull all existing outcomes and their status into a sheet for proofing and updating.

 

I have a template project you can copy. You can also see the entire source on GitHub if you'd like to take a look or contribute. My plans are to eventually convert this to an AddOn for easier distribution and use.

Developer Tools for the Canvas User > Tutorial #3

 

For this tutorial we are going to combine what we learned in tutorial's 1 and 2. The goal will be to make an AJAX request with JavaScript to the Canvas API, and then when the request is successful update the DOM with an updated value. The Document Object Model or DOM, is the webpage as your browser sees it. I'll get you through this tutorial without any more details, but if you're curious here are some resources:

W3 Schools - JavaScript DOM Methods

MDN - Document Object Model (DOM) - Web APIs

 

As part of this rapidly escalating tutorial I am no longer going to use pictures. Anything you need should be referenced from the previous tutorials.

 

  1. Grab the snippet from the last tutorial and add the following code (lines 10-14) to the end.
    var payload = {
         "nickname":"My W○RKR∞M ⸚ Test"     // what we are changing the nickname to
    }

    $.ajax({
         url : '/api/v1/users/self/course_nicknames/1214595',
         type: 'PUT',
         data: payload
    })
    // when the request is resolved
    .done(function(response, status) {
         console.log(response)
    })
    • The jQuery done() method allows us to do something when the AJAX request is complete. For now, copy or type this code into your Console tab, and press Enter
    • The console.log() method allows us to display messages to the console. This is generally used for debugging or displaying other messages while developing. The user will never see these messages unless they have the Console tab open.
    • The response should look just like the one you saw in the Preview pane of the Network tab from Tutorial #2
  2. Now, you will update the name of the Course Card...
    Note: We could have done this with the payload value, but this is a better example of making an AJAX request and doing something when the request is finished and successful.
  3. First we have to find a Selector we can use to identify the element we want to change. 
    Right click on the Course Card where you see the course nickname (the text with color), and Inspect Element
    Hopefully, you will land on a element that looks something like this
    <span style="color:#FDC010;" data-reactid=".1.$1266609.0.2.0.0.0">W○RKR∞M⸚CARROLL</span>
    Note the style="" attribute with value color:#FDC010;
    We will use this as our selector for this tutorial.[1][2]

  4. Let's update our code and use jQuery to update the element after the AJAX request completes, see line 12
    We will use the response.nickname value
    var payload = {
         "nickname":"My W○RKR∞M ⸚ Test"     // what we are changing the nickname to
    }

    $.ajax({
         url : '/api/v1/users/self/course_nicknames/1214595',
         type: 'PUT',
         data: payload
    }).done(function(response, status) {
         $('span[style*="color:#FDC010;"]').html(response.nickname)
    })
    Press Enter, after updating the code in the Console tab
  5. You should see the nickname of your course card update
    If not, try refreshing the page and reset or adjust some of the values you are passing with the code.

 

Congrats, AGAIN! 

This is the basic workflow of a Canvas end-user modification. These are some of the fundamental practices used in making interactive web pages all across the web. You can expand these skills to make your own custom Canvas modifications. Remember to review the Canvas API Documentation and thoroughly plan out the objective and goals your script is trying to achieve.

 

[1] There a plenty of resources on the web for CSS and HTML selectors for interacting with DOM elements via JavaScript, check with Google.

[2] This is because Canvas uses React - A JavaScript library for building user interfaces, which allows elements to load or update after the Primary DOM loads. This is noticeable via the attribute data-reactid="". Usually unique elements will have an id="" attribute if the element is unique and a class="" attribute if there are similar elements. This creates problems when jQuery tries to interact with these elements, because they are not part of the page when jQuery loads. We would prefer to use predictable Selectors whenever possible. This is a more advanced topic and may be covered in a later tutorial.

 

 Rapid Escalation

Repeat Tutorial 3 and update the color of the Course Card, after sending a new color to the Canvas API.

Developer Tools for the Canvas User > Tutorial #2

 

Before getting started with APIs, read through paragraphs 1-5 of the linked thread by Stuart Ryan

Canvas APIs: Getting started, the practical ins and outs, gotchas, tips, and tricks

Stuart confirmed there is a working beta environment on the Canvas Free For Teachers accounts at https://canvas.beta.instructure.com


To save on lengthy screenshots, I've combined some panels, please let me know if this causes confusion.

 

  1. Now that you have the console open, click on the Network tab, and the ⃠ Clear button on the left
    This will clear all the requests that happened during page load
    Drag out some space with the border between the ViewPort (on the left) and the Developer Tools
  2. Now click on the edit button at the top right of any Course Card, change the nickname and the color, click Apply
    You should see two new requests with the course number
  3. Click on the request prefixed with course_ and then the Network Headers tab
    Take a quick peak at the following:
    Request URL - this is the URL (or endpoint) of the request we want to send to the API to change the color, it contains your user and course id's
    MethodPUT - HTTP, and all the Request Methods - HTTP | MDN 
    Status Code200 OK, and all the Response Status Codes - HTTP | MDN 
    Content Typehttps://www.google.com/search?q=JSON
  4. Now click on the Network Preview tab
    This is JSON, I hope you clicked that last link.
    I'll walk you through with Colors first, it's a simple place to start.
    // this is a simple JSON object, with the hex value of the color you chose
    // you'll usually see JSON like you see in the console, with all the white space removed
    {hexcode: "#F0592B"}

    // but it's often useful to nest it with tabs while you're working and learning
    {
         hexcode: "#F0592B" // this is the data that was sent to Canvas to save the color
    }

    // it has one (1) value, simple right?

    Canvas Developer Tools | Change Color

  5. That's 5 pieces of information we need to change the color with the API
    URL - API endpoint/api/v1/users/:id/colors/:asset_string
    MethodPUT - replaces all current representations of the target resource with the request payload.
    ID - your user idself - use self when you can't remember your user_id [1]
    Asset Stringcourse_# - get the course number from the course URL
    Parameters{hexcode: "#F0592B"} // the payload you will PUT to the URL
  6. Let's keep it simple and use jQuery to make this API request
    Type or copy the 10 lines below into the Console tab, and edit the course number in the URL
    After you get this snippet into the console, hit Enter
    var payload = { hexcode: '#FDC010' } // yellow

    // http://api.jquery.com/jquery.ajax/
    $.ajax({
        url  : '/api/v1/users/self/colors/course_1214595',
         type: 'PUT',
         data: payload
    })

    // #8BC34A - a green hex code

    {readyState: 1, setRequestHeader: ƒ, getAllResponseHeaders: ƒ, getResponseHeader: ƒ, overrideMimeType: ƒ, …}

  7. You should immediately see a response that looks something like the one above, we'll cover it in tutorial #3, click on the Network tab
    Review the Network Headers and the most recent request for course_#
    Hopefully you'll see Status Code of 200 OK
    If not, compare your code to the snippet above // comments can be ignored, or take a peak at tutorial 3
  8. Click on the Network Preview tab
    You should see a JSON object with the hexcode you sent with the request in the Console tab
  9. Refresh the page
    Unlike tutorial 1, this time you sent the data to the Canvas API where it was saved. When you refreshed the page, you got another copy of the Dashboard with the new color.
  10. Try It Again!
    Go back to the Console tab. To re-execute the last command/code you ran in the console, press the up arrow on your keyboard
    Copy the green hex code from the snippet, and replace the payload value, press Enter
    Pick a different Hex Code with W3 - HTML Color Picker

 

Congratulations!

You've just used javascriptjqueryajax, and the Canvas api to Update custom color - Users - Canvas LMS REST API Documentation 

Review the documentation anytime you want to interact with Canvas programmatically. The documentation is a great starting point to any project, then planning how you will use it in your script or program.

 

 Escalating

 

  1. Let's continue to the Course Nickname.
    Click on the Network request without the course_ prefix, in the screenshot below it's 1214595
    Review the Headers and the Preview tabs as you did above
    Canvas Developer Tools | Set Course Nickname
  2. Some more JSON, this time with a few more parameters, let's take a look
    // you see a string like this
    {"course_id":1214595,"name":"W○RKR∞M⸚CARROLL","nickname":"My W○RKR∞M ⸚"}

    // we can indent and format, making it easier to read
    {
         "course_id":1214595,          // the id of the course we want to rename
         "name":"W○RKR∞M⸚CARROLL",     // the current nickname of the course
         "nickname":"My W○RKR∞M ⸚"     // what we are changing the nickname to
    }
  3. Three values were returned in response to setting the Course Nickname using the Dashboard Card. However, we only need to send 1 value to change the nickname.
    Take a look at Set course nickname - Users - Canvas LMS REST API Documentation
    Note the Endpoint and the Method, it looks like this

     PUT /api/v1/users/self/course_nicknames/:course_id

     

  4. Let's update the snippet of code we used in the first section of Tutorial #2

    We need to update the payload with the nickname, and change the URL

    // update the payload with the values we need to set
    // indent them to be easier to read
    var payload = {
         "nickname":"My W○RKR∞M ⸚ Test"     // what we are changing the nickname to
    }

    // http://api.jquery.com/jquery.ajax/
    $.ajax({
         url : '/api/v1/users/self/course_nicknames/1214595',
         type: 'PUT',
         data: payload
    })
  5. Copy and paste your code into the Console tab (unless you edited it there) and press Enter
  6. You should immediately see a response that looks something like the one above, we'll cover it in tutorial #3, click on the Network tab
    Review the Network Headers and the most recent request for course_#, hopefully you'll see Status Code of 200 OK
    If not, compare your code to the snippet above // comments can be ignored, or take a peak at tutorial 3
  7. Click on the Network Preview tab
    You should see a JSON object with the hexcode you sent with the request in the Console tab
  8. Refresh the page
    You should see your course change names
  9. Try It Again!
    Edit the snippet, change the nickname and press Enter

 

[1] Profile - Users - Canvas LMS REST API Documentation

      or in the browser console, try ENV.current_user_id

 

 Rapid Escalation

Check out Developer Tools #3 - Update the DOM with an AJAX Response  and we'll update the Dashboard without Refreshing the page

Developer Tools for the Canvas User > Tutorial #1

 

  1. On your Canvas Dashboard, Right Click on a Course Card and choose Inspect
    If you miss and the highlighted element is not exactly as shown, hover over the elements until you have the whole Course Card
    Look for the <div> elements with a class of ic-DashboardCard
  2. Choose Delete Element
    Canvas Browser Tools - Delete Element
    It's Gone!
    Canvas Browser Tools - Element Deleted
    Not Really.
    And you didn't break anything either. You deleted the element from the browser's local copy of the page, nothing on the server has changed.
    To get a new copy from Canvas, continue to step 3
  3. Refresh the page

 

All Done! After the refreshed page downloads, your Canvas Dashboard is back to normal.

 

There's no real purpose for doing this other than to walk you through finding elements to edit on the page, or to make this tutorial. I'm enrolled in a few more than the three courses seen here. For the average Canvas user this may be helpful for writing tutorials and other documentation, or maybe removing and modifying personally identifiable information to take and transfer screenshots safely.

 

 Escalating

 

  1. To modify an element on the page, right click on it or find it in the Elements tab, and choose Copy Copy Selector
    Canvas Developer Tools | Change HTML with JavaScript
  2. Next, click on the Console tab and type in // and paste the selector, press Enter (that is 2 forward slash's)
    This is a JavaScript comment (code that isn't executed) with an identifier we can use to change the content of the <h1> that displays the Dashboard page title
    You should also see undefined on the line below, this is because nothing was executed and nothing was returned
  3. Using either of the 1 line jQuery* snippets below, you can change the title of the Dashboard page or remove the last Dashboard Card from the page
    // change the page title/header
    $('#dashboard_header_container > div > h1').html('My Dashboard')
     // remove the last dashboard card
    $('.ic-DashboardCard:last').remove()

    Each line should edit the page immediately and the console will respond with an updated DOM object

    Canvas Developer Tools | Change and Delete
  4. Refresh the page to clear your changes

 

* The usage of jQuery here is for demonstration purposes. Canvas currently provides jQuery, however it may be deprecated in the future. The following snippet shows how to change the page Title with vanilla JavaScript.

// change the page title/header
document.querySelector("#dashboard_header_container > div > h1").textContent = "My Dashboard";

 

 

 

 Rapid Escalation

If you want to make changes to your Canvas Dashboard more permanently, check out this thread and Github repository.

Sorting Dashboard Course Cards 

canvancement/dashboard at master · jamesjonesmath/canvancement · GitHub 

 

For a deeper look at modifying Canvas pages with Javascript, look at Hiding Content from Certain Roles

While collaborating recently, I’ve found myself referring to the Javascript Console, or is it Developer Tools, maybe Web Inspector; what about adding Browser before, do I provide a link? Sometimes, I don’t know whether to provide a link to an article that discusses the particulars of opening, inspecting or getting to the tab I want to reference; or if I’m insulting someone. So, I've decided to create a series of short tutorials that will hopefully walk new developers through some basic tooling around on Canvas with a Browser and JavaScript. I will also try to use these as references in future posts and discussions. I hope they are helpful, feedback is welcome. Enjoy!

 

Before we get started, let me point out that I won’t be getting lengthy on how to open the tools in each browser since everyone can do that with Google, and the easiest way is to right click the web page and select Inspect Element or Inspect, if you're using Chrome.

 

The following is a brief, but detailed, and rapidly escalating tutorial of things any Canvas User can do with Developer Tools. Along the way, I will share some community resources that will help guide you with additional information.

 

tutoriallevelfocus (tab in developer tools)
#1 - Delete and modify elements, and Refreshfreshmanelements
#2 - Update a course nickname with the APIsophomorenetwork, console
#3 - Updating the DOM and Handling Responsesjuniorconsole, elements
#4 - JavaScript XHR for Canvasseniorconsole, network
#5 - Mutation Observers & Reactmutant

 

// indexing a few related resources

guidelevelfocus
API Testing: Postman by Garth Egbertadvancedapi requests, json

 

 While searching around the community for this series, I stumbled upon this comment by James Jones.

  hiding-content-from-certain-roles#comment-86823 

The problem with JavaScript resources is that, for the basic stuff, you're not trying to learn JavaScript, you're trying to accomplish a specific task. There's no book or website that I want to sit through the whole thing to learn how to program in JavaScript. I don't want to start with "Hello world." I don't have time to start with "Hello world." I want to solve the problem that needs solved and get back to life.

 

My primary resources are the encyclopedia (Mozilla Developer Network documentation) and the commentary on it (Stack Overflow), using Google to get me to the content I need. I often start with a solution from Stack Overflow and then go look up the right way to do it using MDN.

I'll also add that W3 and W3Schools are great resources for what we're doing.

 

If you have questions or need assistance, please ask in a comment, it will help others.

If you work through these tutorials and find any issues (or Canvas breaking changes) please let me know and I will get it fixed right away.

Please let me know if you would like to contribute, I would be happy to add new tutorials and information. Contribute new tutorials with API endpoints that work for user/student roles, no advanced permissions.

Mike Cowen

Collapse & Expand Modules

Posted by Mike Cowen Employee Jul 5, 2018

For various reasons I decided to write a little CSS & JS to do the following:

  1. Load the modules page with all modules collapsed by default
  2. Create a button on the modules page to Expand/Collapse all modules
  3. When a user clicks on a link that takes them to a module in the modules page, make the modules page load with all modules collapsed EXCEPT the module that was clicked on the previous page.

 

This is what the page looks like when first opened. Notice the button at the top "Expand All Modules."

Screenshot of collapsed modules with button allowing to expand all modules

 

 

This is what the page looks like with the modules expanded. Notice the button at the top "Collapse All Modules."

Screenshot of expanded modules with button allowing to collapse all modules

 

I am putting the code here for others to use and improve.  If you make improvements, please share them with the rest of the community.  I am not a coding professional and consider myself to be an intermediate level, NOT an expert (although I got some help from some experts when I got stuck during this project  .)

 

If you have suggestions, please feel free to let me know. I'm always looking to improve my coding

 

 

**DISCLAIMER**

This code is 100% unsupported by me and/or by Instructure. Use it at your own risk. Always try new code in your test or beta environments first. This will probably break. If you don't have someone on staff who can maintain it or fix it when it breaks, you will want to seriously reconsider using it in the first place.

 

 

Add this to the CSS file:

/*  Collapse all modules. 
     use this in combination with JS to auto-open the module link that was
     clicked to navigate to the page */


#content #context_modules .content,
#content #context_modules .collapse_module_link
{
  display: none;
}

#content #context_modules .expand_module_link {
  display: inline-block;
}

 

Add this to the JavaScript file:

//
// Use in combination with CSS that loads all modules in a collapsed state.
// When navigation to the modules page is to a specific module,
// automagically click the module so it opens in an expanded state.
//
var anchor = window.location.hash;
var underscore = anchor.indexOf("_") + 1;
var characters = anchor.length;
var     module = anchor.substring(underscore,characters);
var selector = "span[aria-controls='context_module_content_"+module+"']";
console.log(selector);

window.onload = function() {expand_module()};
function expand_module() {
    document.querySelector(selector).click();
     console.log("click attempted");
}

//
// Add button and script to expand and collapse all modules
//

// Create the button on Modules pages
if(window.location.href.indexOf("modules") > -1) {
     document.querySelector('.header-bar-right__buttons').insertAdjacentHTML( 'afterbegin', '<button class="btn" id="expand-collapse-modules" status="collapsed" onclick="expand_collapse_modules()"><span class="screenreader-only">Collapse or expand all modules</span>Expand All Modules</button>');
    }

// when the button is clicked, expand or collapse all modules that are not currently expanded or contracted.
function expand_collapse_modules()
{

    if (document.getElementById("expand-collapse-modules").status == "collapsed"){
         document.getElementById("expand-collapse-modules").innerText = "Expand All Modules";
         document.getElementById("expand-collapse-modules").status = "expanded";
          var items = document.querySelectorAll("span[style='display: inline-block;'][aria-expanded='true']");

         }
    else {        
         document.getElementById("expand-collapse-modules").innerText = "Collapse All Modules";
         document.getElementById("expand-collapse-modules").status = "collapsed";
          var items = document.querySelectorAll(".expand_module_link:not([style='display: none;'])");
         }
        
    for (var i = items.length-1; i >= 0 ; i--) {  
        console.log(i);
        items[i].click();
    }
        
}

 

The code is also attached to this blog for your convenience.

I recently had the opportunity to teach in Canvas again for the first time in a little while, and I noticed that my behavior when grading was to always navigate to my instructor to-do-list to launch Speedgrader. However, I had navigate back to the home page to view the to-do-list every time I finished grading all submissions for an assignment. This caused me a lot of frustration as I knew that the to do list was accessible via the API. So I wrote a little bit of code that I have found to be indispensable now to me as an instructor.

 

The following code attaches a little button in Speedgrader to navigate to the next item on the todo list for teachers in the course. If you do not have a to do list on the home page (ie: Admins) you will not see this new button.

And when a teacher has no other assignments in their to do list they get a nice thumbs up indicating this is the last assignment that needs grading. However, the teacher will still need to complete any submissions on that assignment to actually be done grading.

Hope your teacher's find it useful!

var currentURL = window.location.href;
if (currentURL.indexOf('/gradebook/speed_grader?') > -1) {
    var courseID = currentURL.match(/\/courses\/(\d+)/g);
    var myRegexp = /(?:^|assignment_id)=(\d*?)(?:\D|$)/g;
    var doRegexp = myRegexp.exec(currentURL);
    var assignment_id = doRegexp[1];
    // console.log(assignment_id)
    $.get('/api/v1'+ courseID +'/todo?per_page=100', function (response) {
        if (response.length > 0){
            selectNextUrl = parseData(response, assignment_id)
            if(selectNextUrl != false){
                addToUI = insertHTML(selectNextUrl['html_url'])
            } else {
                html = '<div><a id="speed_grader_gradebook_link" class="Button Button--icon-action gradebookActions__Button gradebook-icon-link" title="All done! No more assignments to grade."><i class="icon-like" aria-hidden="true"></i><span class="screenreader-only" aria-hidden="true">All done! No more assignments to grade</span></a></div>'
                $('.assignmentDetails').after(html);
            }
        }
    });
}

var parseData= function(response,id) {
    // console.log(response)
    for (var i = 0; i < response.length; i++) {
        assignment_id = response[i]['assignment']['id'];
        if (String(assignment_id) !== id){
            return response[i]
        }
    }
    return false
}
var insertHTML = function(html_url){
    html = '<div><a href="'+ html_url +'" id="speed_grader_gradebook_link" class="Button Button--icon-action gradebookActions__Button gradebook-icon-link" title="Next Assignment that Needs Grading"><i class="icon-arrow-open-right" aria-hidden="true"></i><span class="screenreader-only" aria-hidden="true">Navigate to Next ToDo Assignment</span></a></div>'
    $('.assignmentDetails').after(html);
}

If you need help knowing where to add the code in Canvas, see this guide: How do I upload custom JavaScript and CSS files to an account?