FALL 2019, ITSE 1302: Computer Programming — JavaScript
Course Overview: This portfolio showcases the application of JavaScript and the jQuery library in building interactive, data-driven web applications. The curriculum emphasizes DOM manipulation, event-driven programming, and the integration of professional UI components to enhance user experience.
This course focused on turning static HTML into functional applications. Below are the primary technical milestones achieved through the Squirrelworks development cycle:
switch statements for seasonal themes and for loops for quiz scoring.clientX/Y), keyboard shortcuts, and complex hover states.Following professional standards, all scripts were developed in a modular fashion—separating structure (HTML), presentation (CSS), and behavior (JavaScript). Projects were staged in a local htdocs environment, tested for cross-browser compatibility, and deployed to KnownHost via FileZilla to maintain the Squirrelworks live production standards.
Created: 10-7-19
This project demonstrates fundamental JavaScript concepts including temporal switch logic, while loop validation, and interactive scoring systems.
Objective: Use the Date() object and a switch statement to provide a time-sensitive greeting to the user upon page load.
var now = new Date();
function greet() {
hour = now.getHours(); // extract the hour from Date object
switch (hour) {
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
return document.write("Good Morning, Current Time:" + now.toLocaleString());
case 11:
return document.write("Happy Lunchtime, Current Time:" + now.toLocaleString());
case 12:
case 13:
case 14:
case 15:
case 16:
return document.write("Good Afternoon, Current Time:" + now.toLocaleString());
case 17:
case 18:
case 19:
case 20:
return document.write("Good Evening, Current Time:" + now.toLocaleString());
default:
return alert("Good Night!");
}
}
Objective: Create a function that manages a "3-strike" guessing system, validates input using case-insensitivity, and returns a point value based on remaining attempts.
function triviaQuiz(i) {
var points = 3;
var guesses = 3;
while (guesses > 0) {
ans = prompt("what is " + triviaArray[i] + " used for?");
// compare lowercase conversion of each string for 'case-insensitive' comparison
if (ans.toLowerCase() == answerArray[i].toLowerCase()) {
alert("correct");
return points;
} else {
alert("incorrect");
guesses = guesses - 1;
points = points - 1;
}
}
return 0;
}
Objective: Implement a while loop that forces the user to enter a valid email format before the script can conclude.
var email = prompt("Please enter your email address");
while (!validEmail(email)) {
alert("ERROR: Email Invalid");
var email = prompt("Please enter your email address");
}
function validEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
| Feature | Logic Employed | Functional Goal |
|---|---|---|
| Randomization | Math.random() |
Picks 1 of 5 quotes from quoteArray on load. |
| Scoring | Accumulator Loop | Aggregates points from 5 rounds of trivia. |
| Metrics | (score*100)/15 |
Calculates the final percentage grade. |
Project 2: Object-Oriented JS →
Transitioning to Frameworks: These projects mark the shift from Vanilla JS to jQuery, focusing on DOM traversal, event delegation, and the jQuery UI Drag-and-Drop API.
Objective: Build a functional shopping interface that updates the DOM in real-time. Key features include a star-rating system and a dynamic cart that supports item removal via event delegation.
Logic: Event Delegation & Siblings
Because "Remove" buttons are created dynamically, .delegate() is used to ensure the click event persists. The script uses .siblings() to grab text from the figcaption of the specific item clicked.
// Adding items to the cart
$('.add').click(function(){
var mytext = $(this).siblings('figcaption').text();
count++;
if (count > 0){
$('#empty').hide();
var listitem = "<li>" + mytext + delbtn + "</li>";
$('#cart').append(listitem);
}
});
// Removing items using delegation
$('body').delegate('.del','click',function(){
$(this).parent().remove();
count--;
if (count == 0) { $('#empty').show(); }
});
Objective: Implement a "User-First" shopping experience using jQuery UI. Users can drag product images into a "Cart" or "Wishlist" and move items between lists using sortable connectivity.
Logic: Droppable Targets & Revert States
Items are initialized with revert: true so they snap back if dropped outside a target. The drop function identifies the source of the drag to determine if it should extract an alt attribute or move existing html().
// Initialize Draggable Gallery
$('#gallery').children().draggable({ revert: true });
// Handle Droppable Logic for Cart
$('#cart').droppable({
drop: function(e, ui){
var iteminfo = ui.draggable.attr('alt');
if(iteminfo){
// If it has an alt tag, it came from the gallery
$('#cartlist').append("<li>" + iteminfo + "</li>");
} else {
// Otherwise, it was dragged from the Wishlist
$('#cartlist').append("<li>"+ui.draggable.html()+"</li>");
ui.draggable.remove();
}
}
});
// Connect lists for sorting
$('#cartlist, #wishes').sortable({ connectWith: ".connectedSortable" });
| Requirement | Project 2 Solution | Project 3 Solution |
|---|---|---|
| Input Method | Click Events (.click) |
Drag & Drop (.draggable) |
| Data Source | DOM Text (.text()) |
Image Attributes (.attr('alt')) |
| State Management | Manual Counter & Toggle | jQuery UI revert & sortable |
| Feedback | Image Swapping (Stars) | Visual Snapping & Sort Animation |
Data Architecture: SQL Functions & Aging →
The "Living" Webpage: This project uses the JavaScript Date() object to programmatically alter the site's CSS, background imagery, and seasonal tips without manual updates.
Objective: Capture the current month and use a switch statement to define a specific "Season" object containing unique colors, background images, and content indices.
Primary Syntax:
var now = new Date();
var monthNumeral = now.getMonth(); // returns 0-11
switch(monthNumeral) {
case 11: case 0: case 1:
season = "Winter";
backgroundImg = "winterbg.jpg";
seasonColor = "#00f";
seasonIndex = 0;
break;
case 2: case 3: case 4:
season = "Spring";
backgroundImg = "springbg.jpg";
seasonColor = "#d7d";
seasonIndex = 1;
break;
// ... Logic continues for Summer and Fall
}
Objective: Utilize the seasonIndex derived from the temporal logic to pull long-form HTML content from a tips array and a specials array, then inject it into the DOM.
Primary Syntax:
// Content storage
var tips = ["<p>Winter tips...</p>", "<p>Spring tips...</p>", ...];
var specials = ["<p>Roses for your sweetheart!</p>", ...];
// DOM Injection
$('#month').html(months[monthNumeral] + " Tips");
$('#specials > p').html(specials[monthNumeral]);
$('#seasontips').html(tips[seasonIndex]);
Objective: Use jQuery to modify the body background and specific heading colors to match the current season's visual palette.
// Visual override based on seasonal variables
$('body').css('background-image', 'url(' + backgroundImg + ')');
$('#month').css('color', seasonColor);
$('.season').text(season);
| Season | Logic Range (Months) | Theme Color | Background Asset |
|---|---|---|---|
| Winter | Nov, Dec, Jan | #00f (Blue) | winterbg.jpg |
| Spring | Feb, Mar, Apr | #d7d (Pink/Purple) | springbg.jpg |
| Summer | May, Jun, Jul | #006400 (Dark Green) | summerbg.jpg |
| Fall | Aug, Sep, Oct | #930 (Burnt Orange) | fallbg.jpg |
Advanced SQL: String Manipulation & Date Types →
Interactive Discovery: This project implements advanced jQuery event listeners to manage hidden data layers, tracking mouse coordinates for dynamic image positioning and utilizing global keypress events for rapid navigation.
Objective: Display preview images that follow the user's mouse cursor. The script captures clientX and clientY coordinates to position a hidden div exactly where the user is looking.
Primary Syntax:
$('.pic').hover(
function(event) {
// Capture ID from title attribute and calculate offset coordinates
picTitle = '#' + $(this).attr('title');
x = 150 + event.clientX;
y = event.clientY;
// Apply coordinates to CSS and reveal the element
$(picTitle).css({'top': y, 'left': x}).show();
},
function() {
// Hide the element when mouse leaves
picTitle = '#' + $(this).attr('title');
$(picTitle).hide();
}
);
Objective: Enhance accessibility by allowing users to jump to specific alphabetical sections of the glossary by pressing the corresponding key on their keyboard.
Primary Syntax:
$(document).keypress(function(evt) {
// Convert character code to string and ensure lowercase
var keyPressed = String.fromCharCode(evt.which).toLowerCase();
// Update window location to the corresponding ID (e.g., #a, #b, #c)
window.location = "#" + keyPressed;
console.log("Jumping to section: " + keyPressed);
});
Objective: Cleanly manage the display of botanical names. Clicking a flower row hides all other open botanical names before revealing the specific child element for the selected item.
$('.flower').click(function(){
// Reset state: hide all botanical classes
$('.botanic').hide();
// Show only the child of the clicked element
$(this).children('.botanic').show();
});
| Trigger Event | JavaScript Method | Resulting Action |
|---|---|---|
| Mouse Hover | .hover() + clientX/Y |
Contextual image preview at cursor position. |
| Key Press | .keypress() |
Alphabetical anchor navigation (Jump-to-ID). |
| Click | .click() + .children() |
Reveal hidden botanical nomenclature. |
| Page Load | $(document).ready() |
Initialization of hidden data states. |
Advanced SQL: String Manipulation & Date Types →
Interactive Form Handling: This project introduces UI state management using jQuery slideToggle() and conditional text updates to create a space-saving, accordion-style newsletter signup.
Objective: Implement a hidden-by-default form that slides into view when prompted. This enhances the user experience by reducing initial page clutter while keeping essential conversion tools accessible.
Primary Syntax:
$(document).ready(function() {
// Ensure the form is hidden on initial load
$('#newsSignup').hide();
// Trigger toggle on click
$('#signuplink').click(function() {
$('#newsSignup').slideToggle();
// Update the visual indicator (+/-) based on visibility
var display = $('#openclose').text();
if (display == "+") {
$('#openclose').text("-");
} else {
$('#openclose').text("+");
}
});
});
Objective: Lab 7 maintains the robust seasonal logic from Lab 5, ensuring that while new UI features are added, the site’s core identity remains tied to the current temporal context.
Execution Detail:
#month header continues to pull from the months[] array.backgroundImg and seasonColor variables still drive the $('body').css() updates.seasonIndex switch result.| Element | Action | jQuery Method | Visual Result |
|---|---|---|---|
| Newsletter Form | Toggle Visibility | .slideToggle() |
Animated slide up/down effect. |
| Indicator Span | Update Text | .text() + Conditional |
Switches between "+" and "-". |
| Header/Body | Style Injection | .css() |
Theme colors match current month. |
Final Milestone Reached: Return to Portfolio Home →
Scaling with Plugins: This project demonstrates how to initialize third-party jQuery plugins (SmartMenus) and build a custom photo gallery that swaps attributes dynamically to create a seamless viewing experience.
Objective: Replace standard horizontal navigation with a professional, collapsible menu system. This involves linking the jquery.smartmenus.min.js plugin and initializing it with custom slide animations.
Primary Syntax:
$(document).ready(function() {
// Apply SmartMenus logic to the navigation list
$('.sm').smartmenus({
showFunction: function($ul, complete) {
$ul.slideDown(250, complete);
},
hideFunction: function($ul, complete) {
$ul.slideUp(250, complete);
}
});
});
Objective: Create a gallery where clicking a thumbnail updates a main "Large Picture" display. The script creates a new Image() object in memory to handle the source transfer and updates the caption text simultaneously.
Primary Syntax:
$('#gallery img').click(function(){
// Create an image object in memory
var thumbnail = new Image();
var alttext = $(this).attr('alt');
// Assign the clicked source to our memory object
thumbnail.src = $(this).attr('src');
// Update the main 'Hero' image and caption
$('#lgPic').attr('src', thumbnail.src);
$('#lgTitle').text(alttext);
});
Objective: Provide immediate visual feedback to the user by highlighting thumbnails on mouseover using border and box-shadow manipulation.
$('#thumbs img').mouseover(function(){
$(this).css('border','darkgreen 2px solid');
$(this).css('box-shadow', '5px 5px 5px #444');
});
$('#thumbs img').mouseout(function(){
$(this).css('border', 'none');
$(this).css('box-shadow', 'none');
});
| Component | Library / Tool | Implementation Type | UX Benefit |
|---|---|---|---|
| Global Nav | SmartMenus.js | Plugin Initialization | Consistent, responsive navigation. |
| Main Display | jQuery .attr() |
Attribute Injection | High-resolution preview on demand. |
| Thumbnails | CSS Pseudo-hover | Event-based Styling | Clear visual "Focus" state. |
Next Step: Review Full Portfolio Architecture →
Professional UI Patterns: This project leverages the full power of the jQuery UI library to organize complex information into digestible, interactive components like accordions and tabbed panels.
Objective: Use the .accordion() method to stack "Plant Overview," "Plant Details," and the "Photo Gallery" into a single vertical space. This allows users to expand only the information they currently need.
Primary Syntax:
$(document).ready(function() {
$("#accordion").accordion({
animate: 900, // Smooth transition speed
collapsible: true, // Allows closing all panels
active: false // Start with all panels closed
});
});
Objective: Implement pop-up dialog boxes for promotional sales and technical data (like the Zone Map). The dialog is initialized as autoOpen: false and triggered by a specific click event.
Primary Syntax:
// Initialize the hidden dialog
$("#zone1").dialog({
autoOpen: false,
height: 600,
width: 800
});
// Trigger the dialog on click
$("#zonePopup").click(function(){
$("#zone1").dialog('open');
});
Objective: Enhance the "Roses" section with .tabs() for categorized browsing and .tooltip() for providing supplemental data (like image links) without leaving the page.
// Initialize tabbed navigation with a slide effect
$("#tabs").tabs({
hide: "slideUp"
});
// Implementation of 'tracking' tooltips for all title attributes
$('[title]').tooltip({
track: true
});
| UI Component | jQuery Method | Logic Applied | Functional Result |
|---|---|---|---|
| Content Stacking | .accordion() |
collapsible: true |
Saves vertical screen real estate. |
| Information Popups | .dialog() |
autoOpen: false |
Displays complex data on-demand. |
| Categorized Data | .tabs() |
hide: "slideUp" |
Segments content into logical groups. |
| Supplemental Info | .tooltip() |
track: true |
Contextual help follows mouse cursor. |
Full Portfolio Module Complete. ← Return to Squirrelworks Dashboard