I am attending an entry level HTML/CSS/JS course and our first assignment is to make a simple website about ourselves. We need to have a horizontal menu that when clicked displays certain information. For example, clicking "description" should display a short paragraph describing ourselves. From what I've researched it seems that my answer lies with using JQuery but I don't believe he expects us to know that nor utilize it this early. Is there another option that I may not be seeing?
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style.css">
<title>Jeremy Ortiz</title>
<div id="header">
<h1>A Little About Jeremy Ortiz</h1>
</div>
</head>
<body>
<img src="hwpic.jpg" alt="Me">
<div id="content">
<div id="nav">
<h2>Navigation</h2>
<ul>
<li><a class="selected" href="">Description</a></li>
<li>A form</li>
<li>Course List</li>
<li>Table</li>
<li>Contact Information</li>
</ul>
</div>
</body>
</html>
#header {
padding: 10px;
background-color: #6CF;
color: white;
text-align: center;
}
img {
position: absolute;
right: 7px;
bottom: 148px;
z-index: -1;
}
#content {
padding: 10px;
}
#nav {
width: 180px;
float: left;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
My answer will assume your goal is to accomplish this task using basic Javascript instead of changing pages by navigating the user using the <a> elements. I understand that there are more efficient methods of performing this but I chose to present the information in a hopefully simple easily readable manner.
The way I would accomplish this is by changing your <a> elements:
<a class="selected" href="">Description</a>
To button elements and add the 'onclick' property with the function to call when the button is clicked:
<button onclick="displayDescription()">Click Me</button>
Now we need to create the elements that will be displayed upon clicking the button. For this we create some <div> other container that we can hide until the corresponding button is clicked.
<div id="description" style="display: none;">
Displayed when the description button is clicked.
</div>
Note** For every button we will need to create a <div style="display: none;"> to hide the information until its corresponding button is clicked.
Now we can create our Javascript function:
function displayDescription() {
var x = document.getElementById('description');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
Note once again that in this method each Javascript function will map to a button in the same way each hidden will map to the same button.
If you need more help I recommend checking out w3schools and specifically for this problem here is a link to what you need to accomplish with your assignment.
http://www.w3schools.com/howto/howto_js_toggle_hide_show.asp
I hope this was helpful as I just wrote this during one of my college classes I will probably formalize my answer more at a later time today.
Related
How would I be able to simplify this jquery code. I feel like I am repeating myself and just wondering if there is a shorter way to write this which I'm sure there is. I am a bit new to javascript and jquery. I have created a two tabs with their own containers with miscellaneous information in them. Basically I want the container to open when it's related tab is clicked on. I also would like the tab to be highlighted when it's active. Also, how would I be able to write code to make all tab containers disappear when you click off from the tab containers.
<!-- HTML Code -->
<div class="sort-filters">
<span class="sort-by active">SORT BY</span>
<span class="filter">FILTER</span>
</div>
<div class="sort-containers">
<div class="sort-by-container">Sort by click me here</div>
<div class="filter-container">Filter click me here</div>
</div>
/* CSS */
.sort-filters {
display: flex;
width: 500px;
height: 30px;
}
.sort-by,
.filter {
background: #CCC;
color: #756661;
flex: 1;
display: flex;
justify-content: center;
align-items: center;
font-family: 'Arial', sans-serif;
cursor: pointer;
}
.sort-by-container,
.filter-container {
width: 500px;
background: #756661;
color: #FFF;
height: 100px;
display: none;
}
.active {
background: #756661;
color: #FFF;
transition: 0.2s;
}
// Jquery Code
js = $.noConflict();
var sort = js('.sort-by');
var filter = js('.filter');
var sortContainer = js('.sort-by-container');
var filterContainer = js('.filter-container');
js(sort).click(function() {
js(filterContainer).hide();
js(sortContainer).show();
js(sort).addClass('active');
js(filter).removeClass('active');
});
js(filter).click(function() {
js(sortContainer).hide();
js(filterContainer).show();
js(filter).addClass('active');
js(sort).removeClass('active');
});
In order to avoid such repetitive actions I like to stick to naming conventions, so that I can apply the ID's, classes or attributes from one element to select other elements, for instance:
<div id="tabs">
<span class="active" data-type="sort-by">SORT BY</span>
<span data-type="filter">FILTER</span>
</div>
Now, all you need is one click handler on #tabs span, and get the data-type of the span you clicked on. You can use that to filter on the classes of the other container elements.
The second thing is that you can attach handler to more than 1 element at the same time. So in your example, js('#sort-containers div').hide(); will hide all the div's that match the selector at once.
results
I changed some classes to ID's, and some classes to data attributes. Here's a fiddle: https://jsfiddle.net/mq9xk29y/
HTML:
<div id="tabs">
<span data-type="sort-by">SORT BY</span>
<span data-type="filter">FILTER</span>
</div>
<div id="sort-containers">
<div class="sort-by-container">Sort by click me here</div>
<div class="filter-container">Filter click me here</div>
</div>
JS:
js = $.noConflict();
var $tabs = js('#tabs span');
$tabs.click(function() {
var $clicked = js(this); //get the element thats clicked on
var type = $clicked.data('type'); //get the data-type value
$tabs.removeClass('active'); //remove active from all tabs
$clicked.addClass('active'); //add active to the current tab
js('#sort-containers div').hide(); //hide all containers
js('.' + type + '-container').show().addClass('active'); //add active to current container
});
As long as you follow the naming convention of data-type: bla in the tabs, and bla-container on the classes in sort-container, you never have to worry about coding for additional tabs.
There might still be things that could be further optimised, but at least it'll take care of the repetition.
First off, hello! I'm new to this website so I apologize for any errors that I make posting-wise.
I am in a web technology class where we are learning JavaScript. In a previous class we learned HTML5 and CSS. Our current assignment is to make a webpage that will either display 1 of 3 images or no images when the user enters the corresponding word in the prompt window.
I was wondering if there was a way to account for user-entered typos? For example, I have in the code "Spn" but was wondering if there was a way to easily make it so that if a user were to enter "Son" by mistake, they would still be shown the image.
Is there a way to do this without having to add a separate if statement?
Below is the code I have so far, which includes my little "test" to see if I could do this. I thought it had worked when I only had two items (ex: "Spn, "spn"), but when I added a third it stopped working, and now it isn't working again. I may have very well been mistaken that there was ever a success, though.
Oh, also, we are only allowed to use JavaScript, HTML, and CSS. So if you have a solution that is jquery (I have no idea what that is), then thank-you, but I'm afraid I can't use it.
Please let me know if there is any other information that you need and I will gladly supply it to you. Thank-you very much for your help, I very much appreciate it!
-Carly
JavaScript Code (file name is switch.js):
var temp = "None";
function choose()
{
temp = prompt("Spn, DW, SH, or None?");
if (temp == "Spn","spn")
{
document.getElementById("picture").src="first.jpg";
document.getElementById("sub").innerHTML="Supernatural";
document.getElementById("picture").style.visibility="visible";
};
if (temp == "DW","dw","Dw")
{
document.getElementById("picture").src="second.jpg";
document.getElementById("sub").innerHTML="Doctor Who";
document.getElementById("picture").style.visibility="visible";
};
if (temp == "SH","sh","Sh")
{
document.getElementById("picture").src="third.jpg";
document.getElementById("sub").innerHTML="Sherlock";
document.getElementById("picture").style.visibility="visible";
};
if (temp == "None","none")
{
document.getElementById("picture").src="blank.jpg";
document.getElementById("sub").innerHTML="Click button to reveal image";
document.getElementById("picture").style.visibility="hidden";
};
}
HTML Code (file name is userchoice.html):
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="switch.js"></script>
<title>What is this not working I'm going to cry</title>
</head>
<body>
<h1>SuperWhoLock</h1>
<h2 id="sub">Click button to reveal image</h2>
<div id="picblock">
<img src="blank.jpg" id="picture">
</div>
<div id="buttons">
<button onclick="choose()">Choose Picture</button>
</div>
</body>
</html>
CSS code (the file name is style.css):
body
{ background-image:url('background.jpg');
}
h1
{ width: 25%;
text-align: center;
margin-left: auto;
margin-right: auto;
background: black;
color: white;
}
h2
{ width: 25%;
text-align: center;
margin-left: auto;
margin-right: auto;
background: white;
color: black;
}
#picblock
{ width: 25%;
text-align: center;
margin-left: auto;
margin-right: auto;
}
#picture
{visibility:hidden;
}
#buttons
{ text-align: center;
margin-left: auto;
margin-right: auto;
}
Barring the foray into putting intelligence in the code, I will give a rather simplistic approach, detailed below:
Since you are the one who is deciding that "Son" should pull up the image ideally meant for "Spn", we should use a mapping that is created by you yourself. We can have something like this:
`
var spn = "Spn", dw ="DW",sh="SH";
//creating a custom mapping
var dict = {
"Son":spn,
"Sln":spn,
"Spn":spn,
"DW":dw,
"DE":dw,
"SH":sh
}
//Your if would look like:
temp = (dict && dict[temp])?dict[temp]:null;
if (temp && temp.toLower() == "spn")
`
2. For creating that dictionary, you will just have to consider the characters around the letter that you are typing.
Note: This approach assumes you have only these three things to compare. If you want a more generic solution that should work beyond Spn,DW,SH, None, please let me know.
I know how to make an image appear using onclick or onMouseOver but how can I make each click produce the appropriate image not just in the same place but, for example, in a row, next to it's previous apperance? My idea is this: I click on reference1 and a picture1 shows up. Then I click on reference2 and a picture2 shows up next to the picture1 already displayed. Now I click on reference1 again, and I want to see pictures 1,2,1 in a row. How can I do that? My ideal would be to see the row rolling when filled, and a delete button deleting the last image in that row, even making the pictures jump out being called from the text field, but I can search for these myself. My greatest concern for now is new click=new image. Thank you.
Assuming this is relatively simplistic- you could keep track of the current position in a list of images, afterwards create a function that deals with the current image then increments this position. Have the onClick event call this function, and there you are.
An example of this in action, using JQuery, can be viewed here:
http://jsfiddle.net/8Q4LQ/
Here's an example.
<html>
<head>
<style>
.refimg { width: 100px; height: 100px; }
.choices a { margin-right: 2ex; }
.choices img { display: none; }
#target { display:block; width: 500px; overflow-x: scroll; border: 1px solid black; }
</style>
</head>
<body>
Choices:
<div class="choices">
ref1
ref2
<image id="image1" src="image1.gif" class="refimg" />
<image id="image2" src="image2.gif" class="refimg" />
</div>
<br />
Selections: <input type="button" value="Delete" onclick="delImage()" />
<nobr id="target">
</nobr>
<script>
function putImage(src) {
var a = src.cloneNode(true);
a.id = ''; //clear id to prevent duplicate id
target.appendChild(a);
a.scrollIntoView(true);
return false;
}
function delImage() {
var a=target.children;
if (a.length>0) target.removeChild(a[a.length-1]);
}
target.style.height=((target.offsetHeight-target.clientHeight)+100)+'px'; //extend height for scroll bar
</script>
</body>
</html>
I there a way in javascript to make the page jump to a specific location on the page, such as
<span id='jump_to_this_location'></span>
I do not want to re=load page,
2020 Answer
A simple and modern way to do this would be like this:
document.getElementById("jump_to_this_location").scrollIntoView({behavior: 'smooth'});
The behaviour: 'smooth' argument makes the jump... well... smooth. Which is something probably most of you want.
You can set the location.hash property, like this:
window.location.hash = "jump_to_this_location";
You can give it a try here.
If you use jQuery it's pretty simple here is some sample code
Bellow is the #nav where I stored all the clickable links to the articles in this example
Note: I used the goto attribute(custom) to pass the ID for the target Article
<div id='nav'>
<div goto='text1'>Link To Text 1</div>
<div goto='text2'>Link To Text 2</div>
</div>
Here, bellow are the Articles you will be jumping to.
Note: The JavaScript in the last code sample takes the distance of the tag to the top of that page and then scrolls the page down by that same distance measurement taken.
<div id='articles_container'>
<article>
<h1 id='text1'></h1>
<p>
Sample article Paragraph 1
</p>
</article>
<article>
<h1 id='text2'></h1>
<p>
Sample article Paragraph 2
</p>
</article>
</div>
Finally this is the javascript + jQuery that makes it all work, this solution is best when you are working with fixed and layered components.
<script>
$(document).ready(function(){
$('#nav div').click(function(){
var id = "#" + $(this).attr('goto');
var top = $(id).position().top;
$('html').scrollTop(top);
});
});
</script>
javascript jquery
This can be accomplished by first creating an anchor for the page landing spot using HTML.
<a name="jumpHere">somewhere</a>
Once you have the landing site, simply use the JavaScript:
window.location = 'yoursite.html#jumpHere';
I realize this question is five years old, but people still find it, and it seems a shame no one has ever answered it...
Specifically "Without Reloading Page" as asked,
and where there is a name="HERE" or id="HERE" label somewhere in the html ("HERE" is of course an example of any label),
then Javascript can do:
if (navigator.userAgent.match(/Chrome|AppleWebKit/)) {
window.location.href = "#HERE";
window.location.href = "#HERE"; /* these take twice */
} else {
window.location.hash = "HERE";
}
Works for me.
You don't need JS for that.
Accessing yourpage.html#jump_to_this_location will do. This can be done through a link (jump)
The rough sketch illustrates using the id attribute in element section to jump to different parts of the page using the anchor in navigation. That is, in your navigation:
<li></li>
<!DOCTYPE html>
<html>
<head>
<title>Go to section</title>
<style type="text/css">
.navigation {
position: fixed;
background-color: green;
width: 100%;
height: 50px;
margin-top: 0px;
margin-right: 0px;
}
.navigation li {
display: inline;
width: auto;
list-style-type: none;
font-size: 20px;
text-decoration: none;
}
a:hover, {
background-color: white;
}
a: focus {
color: lime;
}
</style>
</head>
<body>
<nav>
<ul class="navigation">
<li>About US</li>
<li>Our clients</li>
<li>Our Offices</li>
<li>Projects</li>
<li>The team</li>
<li>Contact US</li>
</ul>
</nav>
<section id="about">
<div class="about" style="background-color: skyblue; height: 500px;">
</div>
</section>
<section id="clients">
<div class="clients" style="background-color: blue; height: 500px;">
</div>
</section>
<section id="branches">
<div class="branches" style="background-color: lime; height: 500px;">
</div>
</section>
<section id="samples">
<div class="samples" style="background-color: olive; height: 500px;">
</div>
</section>
<section id="team">
<div class="about" style="background-color: grey; height: 500px;">
</div>
</section>
<section id="contacts">
<div class="about" style="background-color: gold; height: 500px;">
</div>
</section>
</body>
</html>
Along with the "#", you might want this CSS attribute: This one "jumps" to the target:
scroll-behavior: auto;
This one smoothly scrolls the screen until it gets to the target:
scroll-behavior: smooth
Reference: https://www.w3docs.com/learn-css/scroll-behavior.html
Caution: It seems to be a relatively new feature, so it may not be available on all Browsers.
Came here trying to find out why my page (1) didn't scroll at all when going to page.com/#hash and (2) why it wasn't scrolling into the correct position when using scrollIntoView(). This solved both my issues, so someone might find it useful too:
window.addEventListener("DOMContentLoaded", () => {
const hash = window.location.hash;
window.location.hash = "";
window.location.hash = hash;
});
If this still doesn't scroll into the correct position then I think that adding a timeout before setting the hash again could do the trick, though I'm not 100% sure on that, someone might be able to correct me here.
Try this (using JavaScript):
location.hash = "div-Name";
I'm in the process of learning Javascript and I'm trying to create a simple dropdown menu.
An example of my desired functionality can be seen on the google homepage in the top menu with the "more" and "settings" dropdown.
I have a ul that is set to display:inline using the onclick() JS event handler. How do I make the ul go back to display:none when I click any where else on the page other than the now visible ul?
I've Googled about blur and setting the focus to another element but I don't know how to actually do it.
I want to do this in straight Javascript, not jQuery.
Here is the html I use:
<div class="info">
Some Text Boom A <a onclick="menu('id1');">Link</a> | More text
<a onclick="menu('id2');">Another Link</a> | more text
<ul id="id1" class="submenu">
<li>A1</li>
<li>A2 This is Long</li>
<li>A3</li>
</ul>
<ul id="id2" class="submenu">
<li>B1</li>
<li>B2</li>
<li>B3</li>
</ul>
</div>
When the user clicks on one of the linked <a> tags, the <ul> which is hidden and directly below the <a> tag becomes visible. I want the <ul> element to dissapear when the user clicks anywhere but the <ul>.
Edit:
Here is my javascript:
function menu(id) {
var myLayer = document.getElementById(id);
if (myLayer.style.display == "none" || myLayer.style.display == "") {
myLayer.style.display = "block";
} else {
myLayer.style.display = "none";
}
}
Edit 2:
Complete CodE:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
<style type="text/css">
a
{
color:blue;
}
.info ul.submenu
{
border: solid 1px #e0e0e0;
background-color: #fff;
position: absolute;
padding: 0;
z-index: 2;
display: none;
}
.info ul.submenu li
{
display: block;
border-top: solid 1px #e0e0e0;
margin: 0px 10px 0 10px;
}
.info ul.submenu li a
{
display: block;
padding: 7px 0px 6px 0;
color: #1177ee;
cursor:pointer;
}
</style>
<script type="text/javascript">
function menu(id) {
var myLayer = document.getElementById(id);
myLayer.onblur = function() {
myLayer.style.display = 'none';
};
if (myLayer.style.display == "none" || myLayer.style.display == "") {
myLayer.style.display = "block";
} else {
myLayer.style.display = "none";
}
}
</script>
</head>
<body>
<div class="info">
Some Text Boom A <a onclick="menu('id1');">Link</a> | More text
<a onclick="menu('id2');">Another Link</a> | more text
<ul id="id1" class="submenu">
<li>A1</li>
<li>A2 This is Long</li>
<li>A3</li>
</ul>
<ul id="id2" class="submenu">
<li>B1</li>
<li>B2</li>
<li>B3</li>
</ul>
</div>
</body>
</html>
This is quite simple actually.
Once you have a reference to the DOM element that you want to bind the blur event listener to, assign it like this:
myLayer.onblur = function() {
myLayer.style.display = 'none';
};
jQuery creates a blur event you can bind a function to, is there a strong reason not to use jQuery? Using a JavaScript library even if it is just for event handling, helps insulate you from browser differences. I've only ever used focus/blur events for text input or textarea elements in a form. It sounds like you want a list to float on top of the other elements. I'd position the list relatively and give it a z-index that is higher than the background. I'd bind a click event to the area outside the list, to dismiss the list pop-up. Is toggling a pop-up/modal window what you want? I'd have a look at jQuery SimpleModal for modal window examples, or look at how one is implemented if you want to roll your own.
If you are looking for a way to stop "onclick" event if it happens inside your menu then "event.stopPropagation();" may be what you need
<body onclick="menu('id1'); menu('id2');">
<div class="info">
Some Text Boom A <a onclick="menu('id1');">Link</a> | More text
<a onclick="menu('id2');">Another Link</a> | more text
<ul id="id1" class="submenu" onclick="alert('click menu'); event.stopPropagation();">
<li>A1</li>
<li>A2 This is Long</li>
<li>A3</li>
</ul>
<ul id="id2" class="submenu" onclick="alert('click menu'); event.stopPropagation();">
<li>B1</li>
<li>B2</li>
<li>B3</li>
</ul>
</div>
</body>