How to craft a more elegant implementation - javascript

I've made an interface for my students where they click an image and hear the description pronounced via text-to-speech, and the text description appears in a div.
Currently I'm calling the text from the image because the onclick event for the speech only works if it's on the div, and since it's a (this) event I don't understand how to combine the two.
First, is it possible, or "better" - to have a single click on the div trigger both functions, rather than splitting them between the div and the image as I've done? This is the only way I could figure out how to get it all working. So that's the first thing.
Second, I'm re-stating this code every time
jQuery(this).articulate('speak')" data-articulate-append=
How can I make this more economical? In reality I have hundreds of items, and there are a bunch more settings in between the jQuery and data-articulate. I've shortened it for this post but in reality it's much longer and repeated hundreds of times.
Last, is it possible to draw the content for the innerHTML from the data-articulate-append part of the TTS command, since it's the same in every case?
Many thanks, I've spent quite a while constructing what I have so far as I'm new to JS. I'm learning and I've tried to answer these questions myself but it's not yet within my skillset, and sorry if I'm not using all correct terminology in my post. I'm including a stripped-down version of the page here, with just the essentials. Any input is greatly appreciated.
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<script src="http://www.clients.brettcolephotography.com/test/jquery-3.1.1.min.js"></script>
<script src="http://www.clients.brettcolephotography.com/test/articulate.min.js"></script>
<link href="http://www.clients.brettcolephotography.com/test/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div>
<div onclick="jQuery(this).articulate('speak')" data-articulate-append="elephant">
<img onclick="elephant()" src="http://www.clients.brettcolephotography.com/test/01.jpg">
</div>
<div onclick="jQuery(this).articulate('speak')" data-articulate-append="camel">
<img onclick="camel()" src="http://www.clients.brettcolephotography.com/test/02.jpg">
</div>
<div onclick="jQuery(this).articulate('speak')" data-articulate-append="bear">
<img onclick="bear()" src="http://www.clients.brettcolephotography.com/test/03.jpg">
</div>
</div>
<div id="word">
</div>
<script>
function elephant() {
document.getElementById("word").innerHTML ="elephant";
}
function camel() {
document.getElementById("word").innerHTML ="camel";
}
function bear() {
document.getElementById("word").innerHTML ="bear";
}
</script>
</body>
</html>

You can accomplish this by:
Giving each div a class, for my example its speak. Then add an eventlistener for speak elements. Then in that event listener, you can run multiple functions. You can also get rid of the image's onclick handler.
<div class="speak" data-articulate-append="elephant"><img src="http://www.clients.brettcolephotography.com/test/01.jpg"></div>
<div class="speak" data-articulate-append="camel"><img src="http://www.clients.brettcolephotography.com/test/02.jpg"></div>
<div class="speak" data-articulate-append="bear"><img src="http://www.clients.brettcolephotography.com/test/03.jpg"></div>
$(document).ready(function(){
$(".speak").on("click",function(){
$(this).articulate('speak');
$("#word").html($(this).data("articulate-append"));
});
});

Related

6 javascript tasks assigned to me by my lecturer

I am a complete beginner to javascript. I am also new to this website. I am asking for help to complete an assignment. I have been trying for more than 4 hours by looking at lecture material and online for a solution. It is causing me a lot of unnecessary stress. Before javascript we only used CSS and Html. I was given 6 javascript tasks to manipulate the html file (taskc.html) already given to me.
The tasks are as follows
Make a statement to change contents of h1 from "Welcome" to "Text"
2nd statement should make an new alert window when the page loads that delivers a message explaining what the page is about
3rd statement should change the title to "text"
4th statement should log the contents (innerHTML) of the first paragraph element in the console.
5th statement should hide the contents of the second paragraph when the page loads
6th statement should change the contents of the header to have a new colour of your choice
Here is that html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Task C - The Document Object Mode</title>
</head>
<body>
<h1 id="header">Welcome</h1>
<p id="first">This site uses JavaScript</p>
<p id="second">Javascript is very useful</p>
</body>
</html>
Because the actual coding im meant to add is meant to be in the .js file I was given. so I figured I had to link the js file in the html file so I added
<script type="text/javascript" src="taskc.js"></script>
With that out of the way I went to the lecture notes and I thought I would simply need to modify some of the code given to me there like
document.getElementById('demo').innerHTML = 'Hello World!';
When I put this code in brackets I got the error (document is not defined)
I modified it to match the requirements for task 1
here it is
document.getElementById('header').innerHTML = 'text';
I was confused because I didn't know what this error meant and of course Errors and how to fix them are never explained so I had to lookup how to resolve the error.
I found that to fix it I have to declare it as a variable so I ended up doing this.
var document = 'taskc.html';
When I did this for document, alert and console all the errors went away, but when I did a live preview only statement 1 was working
If anyone could help me fix this I would really appreciate because I don't understand enough javascript to be able to complete this in a reasonable amount of time.
So first: Please use Javascript functions to keep your code tidy and clean.
Example:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Task C - The Document Object Mode</title>
</head>
<body>
<h1 id="header">Welcome</h1>
<p id="first">This site uses JavaScript</p>
<p id="second">Javascript is very useful</p>
<script type="text/javascript" src="taskc.js">test();</script>
</body>
</html>
function test(){
alert("This is a test!");
}
Always implement scripts that are document referenced at the bottom of your html.
If you use JQuery you can use following code to check document is loaded:
$(document).ready(function(){
//foo bar
});

Changing elements in an HTML file using javascript onclick event

I've been learning HTML and CSS this semester and originally started to code my project in HTML and CSS, but in order for my project to work, I had to link HTML pages to each other. It ended up making a lot of HTML pages just to change one line of text. I've been trying to get a handle on JavaScript to make my project more efficient. My HTML code looks like this:
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Oakwood</title>
<meta name="viewport" content="width=device-width; initial-scale=1.0;">
<link rel=stylesheet type=text/css href=default.css>
</head>
<body>
<div id=back></div>
<div id=drdick></div>
<div id=choice></div>
<div class="typewriter">
<script src="run.js"></script>
<p id=text>While out running someone says “Hi” causing you to trip. He helps you up.</p>
</div>
<div id=move>
<button type="button" onclick="changeThis()">Next</button>
</div>
</body>
</html>
My Javascript Looks like this:
var quoteIndex = 0;
var quotes = [
"Thank you.",
"Are you ok?",
"Yes, I’m not normally this clumsy"
];
function changeQuote() {
++quoteIndex;
if (quoteIndex >= quotes.length) {
quoteIndex = 0;
}
document.getElementById("text").innerHTML = quotes[quoteIndex];
}
function showPic()
{document.getElementById("drdick").src="img/drdickab.png";}
function changeThis() {
changeQuote();
showPic();
}
when I test my code my quotes update how I want them to. My picture does not show up at all. Is there something I am missing when it comes to how HTML and Javascript interact? I have been looking through the forums to figure out what I have wrong, and I haven't been able to figure that out.
Your image is not displaying because you did not specify your image anywhere in your markup, and your javascript is also not enough. But try this inside your body tag:
<body>
<!--replace your button with this code.-->
<div id=move>
<button type="button" onclick="showMyImage();" value="Next"></button>
</div>
<!--I assumed you will display the image just below your button, note that initially your image is hidden and displayed on button click event-->
<div>
<img id="myImage" src="img/drdickab.png" style="visibility:hidden"/>
</div>
</body>
.
<!--There's really no need to have multiple scripts, just one will do the job-->
<script type="text/javascript">
function showMyImage(){
document.getElementById('myImage').style.visibility="visible";
}
</script>

Getting one element to effect multiple images

I am trying to make a page of tiled images which each have a three state roll over effect. I got it to work for the first image but cannot get it to effect the other images. I know it has something to do with me using getElementById but haven't been able to figure out a solution
Current Code:
<!DOCTYPE html>
<html>
<head><link rel="stylesheet" type="text/css"
href="test4.css"/>
<script>
var clicked = false;
function onClick()
{
clicked = true;
document.getElementById("myImage").src="images/in.jpg";
}
function onMouseover() {
if(!clicked)
document.getElementById("myImage").src="images/half.jpg";
}
function onMouseout(obj) {
if(!clicked)
obj.src="images/out.jpg";
}
</script>
</head>
<body>
<img onmouseover="onMouseover()" onmouseout="onMouseout(this)" onclick="onClick()"
id="myImage" src="images/out.jpg" width="167" height="230">
</body>
</html>
PLEASE && THANKS
Your explanation implies that there are many <img/> on your page but your code only shows one. I will assume that your explanation is correct and that are many <img/> for the purposes of this answer.
There can be only one element on the page with a given id. Any more than 1 and the page is invalid and you will see issues like the one you see. Instead of retrieving by id, give all the elements the same class and retrieve with document.getElementsByClassName

How can I make document.write and ajax play nice?

My programming skills are rudimentary at best, so please forgive me if I sound a little clunky discussing these things. I'm learning, but at a chimp's pace.
Here's my issue: I'm using JQuery Mobile to bring in some form content as a dialog via ajax. This content is contained in the document itself, in second div with a data-role="page" attribute.
Within that second page div, I have some javascript that defines a few vars, then writes them into the doc with document.write().
However, when I click the link (the far right link in the nav), instead of popping up a nice dialog, Firefox instead briefly loads a new page with the fist var (not dynamically but as a static page), then redirects back to the starting page, leaving a "wyciwyg(00000)..." in my browser history. Upon said redirect, "WYCIWYG" is displayed in the browser's title bar. Other browsers choke in slightly different ways (Safari doesn't redirect, Chrome displays all the vars and doesn't redirect, etc.), but the WYCIWYG-in-the-history factor is in play in all three. If I remove the document.write commands, the link behaves as expected.
I've scoured the web for hours and not found an answer... similar problems show up in 10 year old Mozilla bug reports, but not much else. The only resolution I've found is not to use document.write() in content loaded via ajax. Unfortunately, I have no clue what the alternative would be, or how I would even begin to execute it. The Javascript code originated at Google - front-end code for a transit trip planner.
Below is some stripped-down code that illustrates the issue. Any guidance would be greatly appreciated, bearing in mind the whole chimp's-pace thing. Thanks in advance.
<!DOCTYPE HTML>
<html>
<head>
<title>WYCIWYG</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.1/jquery.mobile.structure-1.2.1.min.css" />
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/mobile/1.2.1/jquery.mobile-1.2.1.min.css">
<script type='text/javascript' src="http://code.jquery.com/mobile/1.2.1/jquery.mobile-1.2.1.min.js"></script>
<script>
var startExample = "USC";
var endExample = "201 N Los Angeles St.";
var zip = "90012";
</script>
</head>
<body>
<div data-role="page">
<div data-role="navbar">
<ul data-mini="true">
<li>Service 1</li>
<li>Service 2</li>
<li>PLAN TRIP</li>
</ul>
</div>
</div>
<div data-role="page" id="planTrip">
Some document.write js:
<script>
document.write(startExample);
document.write(endExample);
document.write(zip);
</script>
</div>
</body>
You could simply use jQuery.html() on placeholder elements:
Source: http://jsfiddle.net/fiddlegrimbo/suD6s/6/
Demo: http://fiddle.jshell.net/fiddlegrimbo/suD6s/6/show/light/
<div data-role="page" id="planTrip">
Some document.write js:
<p id="start"></p>
<p id="end"></p>
<p id="zip"></p>
<script>
$("#planTrip #start").html(startExample);
$("#planTrip #end").html(endExample);
$("#planTrip #zip").html(zip);
</script>
</div>

How do I call an HTML page to a jQuery tab menu in the div section retaining all functionality?

I'm new to JavaScript and need some help figuring out how to put things together. I need to put my JavaScript image loop html page on my jQuery menu tab page. Here is my jQuery code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness /jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#tabs" ).tabs();
});
</script>
</head>
<body>
<div id="tabs">
<ul>
<li>Home</li>
<li>About me</li>
<li>Contact us</li>
<li>Gallery</li>
</ul>
<div id="home">
<p>A short paragraph about Overcoming Obstacles.</p>
</div>
<div id="about-me">
<p>A short paragraph about me.Banner advertisement that uses a JavaScript function to change the image every few seconds using three images.</p>
</div>
<div id="contact-us">
<p>My contact details.</p>
</div>
<div id="gallery">
<p>This is my gallery.</p>
</div>
</div>
</body>
</html>
The part I need help with is the about me page. I have the image loop created with the page description and it works. What I need to do is call the About_me.html (named Brunson_About_me_rotate2.html) to the jQuery menu tab page with all its functionality. But I only know how to work with HTML, CSS, JavaScript, jQuery, because that's all I understand how to do. It can't be done with Ajax, ASP, PHP, or SPRY because I don't know how to work with them and this is enough of a headache for me right now. And it has to work with the client side, not the server side. Also, this is going into a Dreamweaver page.
I have tried to put the loop code with text into the About us section of the Tab Menu code, but that doesn't work. Alternately, I have tried:
<? include("./Brunson_About_us_rotate2.html");?>
(Because that's what the file name is) trying to call up the loop in the jQuery menu page About us, but that doesn't work either; all I get is a blank page. I'm VERY new to this whole thing and I barely know how to make this happen; it's taken me 5 days to get this much put together. I don't even know what options are available to make it work. Can someone help me figure out what to do? I just need these 2 pages to work together properly when the page is clicked. Thank you for your time.
After getting several options, thank you both for your help by the way, that did not work, I have been working the code around to see what I can do with it. I am posting the code just as it is now and almost what it should look like after it's uploaded to the web. Here's what I have so far:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Brunson - Home</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness /jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#tabs" ).tabs();
});
</script>
</head>
<body>
<div id="tabs">
<ul>
<li>Home</li>
<li>About</li>
<li>Contact</li>
<li>Gallery</li>
</ul>
<div id="home">
<p><h2>What is a Life Coach?</h2></p>
<p>A life coach is someone who is an advocate for you in reaching a higher level of understanding<br />
and being the best person you can be in whatever area of your life you decide you need improvement in.</p>
<p><h2>What does a Life Coach do?</h2></p>
<p>A Life Coach assists you in identifying those areas in your life that you would like to change.<br />
Once those areas are determined, the process of creating the life you truly can begin.</p>
</div>
<div id="about">
<script type="text/javascript">
var pictureArchive= ['image1.jpg','image2.jpg','image3.jpg'];
window.onload=function() {
var o=document.createElement('img');
o.setAttribute('id', 'image');
o.setAttribute('src', pictureArchive[0]);
o.setAttribute('alt', '');
document.body.appendChild(o);
rotate(pictureArchive.length);
}
function rotate(idx) {
if(idx>=pictureArchive.length) {
idx=0;
}
document.getElementById('image').src=pictureArchive[idx++];
timerID=setTimeout('rotate('+idx+')', 4000);
}
</script>
<script>
$(function() {
$( "#tabs" ).tabs();
});
</script>
<p>I became a Life Coach so I could reach more people and make changes in more lives than I was
able to do when I limited myself to my Alternative Therapies Business. By choosing to take the
limits I placed on myself off, I have created abundance in my life and create more value than I
was able to do before. The school I chose to get my Life Coach Certification from was QSCA because
they have the same beliefs that I do. Living the Universal Laws, living my life with integrity,
being the best that I can be, and ascending to higher levels of awareness and consciousness allows
me to help others overcome negative behaviors and limited thinking patterns. Helping others this
way allows me to create a reality that is past the negativeness we have been living with.</p>
</div>
<div id="contact">
<p>My contact details. Form asking for name, email address, and a message. The form will have an unselected radio button array that includes a yes or no response. All fields required. Validation of all fields is a must. Email address must be present and match</p>
<p>the criteria for a legitimate e-mail address (using regular expressions). The submit button must call a validation routine; and when the user has filled in all information correctly, the page will display a thank you message and clear the form. The ehank you message can be s separate page, or it can be displayed on the same page.</p>
<p>Are you ready to make a change in your life right now? Yes No</p>
</div>
<div id="gallery">
<p>Once you make a choice to make a change, old limiting beliefs seem to just fade away.</p>
<p>As nature abhors a vacuum, unlimited beliefs seem to jump to the fore.</p>
<p>Where once there was nothing but limits, suddenly everything is possible.</p>
</div>
</div>
</body>
</html>
What I got with the code ya'll gave me was a blank about page, a page with a box that's window scrolled up and down and side to side and had an error message in it that said IE could not open webpage, and the last code gave me that code on the browser page. So I started just trying to play with the code and see what I could get to work. I almost have what I need. And yes, I do realize that some of the code is not placed correctly, but when I placed it correctly, the images didn't show up at all on any of the pages.
The only problem with the way this is, is that the images are on all the pages; they are just supposed to be on the About page. I'm going to be putting a contact form on the Contact page and 3 different images that fade out, move, and fade in on the gallery page. Then ultimately, after I get done coding this in NotePad and checking it in the browsers to make sure it works, this "page" with all this content included, will go in Dreamweaver that will have the esthetics attached, external links, a clock and then get uploaded. So, does anyone have any ideas as to what I should try next?
Your problem is, that you made the php - tag not correct.
<?php include("../Brunson_About_us_rotate2.html"); ?>
And you also must put two points to get to the parent directory.
Ajax seems a very easy solution for this.
jQuery already has it's own easy to use ajax functions.
One of them being .load() http://api.jquery.com/load/
$('#about-me').load('../Brunson_About_us_rotate2.html');
Another option would be iframe
<div id="about-me">
<iframe src="../Brunson_About_us_rotate2.html"></iframe>
</div>
http://www.w3schools.com/tags/tag_iframe.asp

Categories