Does anyone know how to create a menu without exiting the page? I want to create a settings menu.
<style>
.material-symbols-outlined {
align: right;
font-variation-settings:
'FILL' 0,
'wght' 400,
'GRAD' 0,
'opsz' 48
}
</style>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD#20..48,100..700,0..1,-50..200" />
<a OnClick="open()" <span class="material-symbols-outlined">
engineering
</span></a>
<div class="menu">
<p>Settings</p>
</div>
(I know that i should not use onclick but i don't know how to use anything else)
<script>
function show(){
div.menu.show=(true)
}
</script>
I wanted it to show div but div is always shown
Welcome!
you want to use style="display:none" on your div
and in the show() function, you want to try this :
document.getElementsByClassName('menu')[0].style.display = "block";
The issue why your <div> is always showing is that you never used any CSS to hide it, and the reason why your onClick handler isn't working is because you are calling a function that hasn't been defined.
You can add an event listener to the link and toggle the .style.display attribute of the menu.
document.getElementById('openMenu').addEventListener('click', () => {
const menu = document.getElementById('menu');
if (menu.style.display === 'block') menu.style.display = 'none';
else menu.style.display = 'block';
});
#menu {
display: none;
}
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD#20..48,100..700,0..1,-50..200" />
<a id="openMenu">
<span class="material-symbols-outlined">engineering</span>
</a>
<div id="menu">
<p>Settings</p>
</div>
Related
I am new to JavaScript. I created this code in order to try and make buttons that will hide
and show certain pictures on the page. I have 3 buttons, the first of which is supposed to run my JavaScript code in <script></script> tags, the other two just have Javascript code inside them and they work fine. But they don't hide the picture once they are clicked a second time, which is why I am trying to do that for the first one if possible.
For some reason, I cannot get the first button with "open()" to work the way I want with my Javascript code. Can anyone with more experience please explain to me what I am doing wrong? Thank you in advance...
var btn1 = document.getElementById('1');
var btn2 = document.getElementById('2');
var btn3 = document.getElementById('3');
var display1 = btn1.getAttribute('display')
var display2 = btn2.getAttribute('display')
var display3 = btn3.getAttribute('display')
function open() {
if (display1 === ('none')) {
btn1.setAttribute('display', 'block');
} else {
btn1.setAttribute('display', 'none');
}
}
<img id="1" src="forge.PNG" style="height:320px; display:none; padding:10px">
<img id="2" src="lizard.jpg" style="height:320px; display:none; padding:10px">
<img id="3" src="walkway.jpg" style="height:320px; display:none; padding:10px">
<button onclick="open()">1</button>
<button onclick="document.getElementById('2').style.display='block'">2</button>
<button onclick="document.getElementById('3').style.display='block'">3</button>
I'd use event delegation to watch for clicks on the container. When the nth button is clicked, select the nth image, and toggle a class that hides/shows the image:
const images = document.querySelectorAll('img');
const buttons = [...document.querySelectorAll('button')];
document.addEventListener('click', (e) => {
if (e.target.matches('button')) {
const i = buttons.indexOf(e.target);
images[i].classList.toggle('hidden');
}
});
.hidden {
display: none;
}
<img id="1" src="https://www.gravatar.com/avatar/34932d3e923ffad9a4a1423e30b1d9fc?s=48&d=identicon&r=PG&f=1" style="height:320px; padding:10px" class="hidden">
<img id="2" src="https://www.gravatar.com/avatar/978ec0c47934c4b04401a8f4b4fec8bd?s=32&d=identicon&r=PG&f=1" style="height:320px; padding:10px" class="hidden">
<img id="3" src="https://lh3.googleusercontent.com/-uIr21N5ccCk/AAAAAAAAAAI/AAAAAAAAHeg/ohNEkpJKXQA/photo.jpg?sz=32" style="height:320px; padding:10px" class="hidden">
<button>1</button>
<button>2</button>
<button>3</button>
Problems with your original code include:
You're trying to select the elements before they exist in the DOM
Elements do not have a display property - in order to check the style of an element, you have to access its .style property first (eg, someImage.style.display)
Similarly, to set the style of an element, you have to set a property of its style property (eg someImage.style.display = <newDisplay>). Setting the display attribute of the element won't do anything.
Try to avoid inline handlers if at all possible - they have many problems and are pretty much universally considered to be quite poor practice. Always attach listeners properly using Javascript instead, whenever that's an option.
The event listener is the better solution, but if you want to see a working code in your way:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>switchpics</title>
</head>
<script type="text/javascript">
var open = function(param) {
img = document.getElementById(param.innerHTML);
if (img.style.display == 'none'){
img.style.display = "block";
} else {
img.style.display = "none";
};
};
</script>
<body>
<img id="1" src="1.jpg" style="height:20px; display:block; padding:10px">
<img id="2" src="1.jpg" style="height:20px; display:none; padding:10px">
<img id="3" src="1.jpg" style="height:20px; display:none; padding:10px">
<button onclick="open(this)">1</button>
<button onclick="open(this)">2</button>
<button onclick="open(this)">3</button>
</body>
</html>
I want to display a <div> block when mouse enters an element
My code so far:
<div class="dropdown">
MEN
<div class="dropdowncontent" id="ddmen" style="margin-left:100px;">
TOPWEAR <br/>
BOTTOMWEAR </br>
FOOTWEAR
</div>
</div>
JavaScript Code:
var ddm=document.getElementById("ddmen")
function ddmenin()
{
ddm.style.display="block";
}
function ddmenout()
{
ddm.style.display="none";
}
But when i hover over <a href="#men"> I cannot click on the links in the <div> with class="dropdowncontent" as the block disappears when i leave the <a href="#men">
I don't understand why this is happening since i have used onmouseover, which is valid even for child elements.
I have tried doing it using css but for some reason the following does not work (Style.css is used in above html)
STYLE.CSS
.dropdowncontent{
display:none;
}
.dropdown:hover .dropdowncontent{display:block;}
Can someone please correct my code to satisfy my needs or has any other simple alternative?
Well, your div link container is not part of a link, so when you move cursor to dropdown menu you leave the link and onmouseout listener does its job.
What you want is to hide the menu when it's not needed anymore. E.g. you clicked on the menu item or you left the menu and didn't return for some time.
To achieve this you can do the following:
Add hiding the menu to click listener on menu items
Add a function that starts some timer as soon as you leave the dropdown button or the menu (so that makes two onmouseout listeners). If you return there, you can reset the timer in onmouseover. When timer is done you can hide the menu.
It can look like this:
const $ = document.querySelector;
let menuTimeoutId;
const menu = $('#ddmen');
function stopMenuTimeoutAndShowMenu() {
if (menuTimeoutId) {
clearTimeout(menuTimeoutId);
menuTimeoutId = null;
}
menu.style.display = 'block';
}
function startMenuTimeout() {
window.menuTimeoutId = setTimeout(() => {
menu.style.display = 'none';
}, 2000); // possible timeout value
}
$('#men, #ddmen').addEventListener('onmouseover', stopMenuTimeoutAndShowMenu);
$('#men, #ddmen').addEventListener('onmouseout', startMenuTimeout);
I think you should use the onmouseover and onmouseout in your <div class="dropdown"> instead. Because, when you go to the div.dropdowncontent you probably invokes the onmouseout event. So the code will be like this:
<div class="dropdown" onmouseover="ddmenin()" onmouseout="ddmenout()">
MEN
<div class="dropdowncontent" id="ddmen" style="margin-left:100px;">
TOPWEAR <br/>
BOTTOMWEAR </br>
FOOTWEAR
</div>
</div>
See if it works ;D
You can try simple CSS changes, that can even help you :
In your Style.css file:
.dropdown .dropdowncontent {
visibility: hidden;
}
.dropdown:hover .dropdowncontent {
visibility: visible;
}
Sorry for the lack of knowledge but I don't know where else to turn. I had been working on the CSS for a project while the javascript was handled by a colleague. That colleague has now left the company and I have to finish his work to hit a deadline with very little knowledge of javascript. He had created a simple function (show/hide) that allowed us to show and hide content with an unordered list. Namely when you click on a list item, the corresponding div shows and the rest hides.
This was working fine, however I have since been asked to duplicate this so that multiple (show/hides) can be used on the page. When I did this the first one works ok, but the next scripts intefere with eachother and also hide content in the other divs. I've tried to fix this using my non-existent knowledge of javascript but to know avail (attempt is below). Any help here would be massively appreciated. Thanks in advance!
function toggle(target) {
var artz = document.getElementsByClassName('history');
var targ = document.getElementById(target);
var isVis = targ.style.display == 'block';
// hide all
for (var i = 0; i < artz.length; i++) {
artz[i].style.display = 'none';
}
// toggle current
targ.style.display = isVis? 'none' : 'block';
return false;
}
function toggle2(target) {
var artz2 = document.getElementsByClassName('vision');
var targ2 = document.getElementById(target2);
var isVis2 = targ.style.display == 'block';
// hide all
for (var i = 0; i < artz2.length; i++) {
artz2[i].style.display = 'none';
}
// toggle current
targ2.style.display = isVis2? 'none' : 'block';
return false;
}
jQuery(document).ready(function($) {
$('.slide-menu li a').on('click', function(){
$(this).parent().addClass('current').siblings().removeClass('current');
});
});
.container {
float: left;
}
.display-item {
display: none;
}
.display-item:first-of-type {
display: block;
}
.slide-menu li.current a {
color: #75aaaf;
pointer-events: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class="container">
<ul class="slide-menu" id="first">
<li class="current">1348</li>
<li>1558</li>
<li>1590</li>
</ul>
<div class="display-item history" id="1348" style="display:block;">History Content</div>
<div class="display-item history" id="1558">History Content2</div>
<div class="display-item history" id="1590">History Content3</div>
</div>
<div class="container">
<ul class="slide-menu" id="second">
<li class="current">Introduction</li>
<li>Highways</li>
<li>Transport</li>
</ul>
<div class="display-item vision" id="base" style="display:block;">Vision Content</div>
<div class="display-item vision" id="highways">Vision Content2</div>
<div class="display-item vision" id="transport">Vision Content3</div>
</div>
I think your code is okay if you intend duplicating the first toggle function in toggle2 function all you have to do is
Change the onclick event function from toggle to toggle2
<div class="container">
<ul class="slide-menu" id="second">
<li class="current"><a href="#/"
onclickk="toggle2('base');">Introduction</a></li>
<li><a href="#/"
onclick="toggle2('highways');">Highways</a></li>
<li><a href="#/"
onclick="toggle2('transport');">Transport</a></li>
</ul>
<div class="display-item vision" id="base"
style="display:block;">Vision Content</div>
<div class="display-item vision" id="highways">Vision
Content2</div>
<div class="display-item vision" id="transport">Vision
Content3</div>
</div>
This really isn't the way to set this up as it just causes the code to grow as more items need to be shown/hidden and the new code is largely the same as the old code. The original code also is more complex than it need be.
The following code will work no matter how many container structures you put on the page as long as you keep the structure the same as it is now. No ids are needed. No JQuery is needed either. You'll never need to touch the JavaScript, just add/remove HTML containers as you see fit.
See comments inline for details on what's happening.
.container {
float: left;
border:1px solid #e0e0e0;
margin:10px;
width:25%;
padding:3px;
}
/* Don't use hyperlinks <a></a> when you aren't
navigating anywhere. If you just need something
to click on, any element will do.
We'll just style the clickable elements to look like links
*/
.slide-menu > li {
text-decoration:underline;
cursor:pointer;
color: #75aaaf;
}
.hidden { display: none; } /* This class will be toggled upon clicks */
<!--
Don't use hyperlinks <a></a> when you aren't
navigating anywhere. If you just need something
to click on, any element will do.
The elements that should be hidden by default
will be so because of the "hidden" class that
they start off with.
No JQuery needed for this. Keep the HTML clean and
do all the event binding in JavaScript (no onclick="...")
-->
<div class="container">
<ul class="slide-menu">
<li class="current">1348</li>
<li>1558</li>
<li>1590</li>
</ul>
<div class="history" id="1348">History Content</div>
<div class="history hidden" id="1558">History Content2</div>
<div class="history hidden" id="1590">History Content3</div>
</div>
<div class="container">
<ul class="slide-menu">
<li class="current">Introduction</li>
<li>Highways</li>
<li>Transport</li>
</ul>
<div class="vision" id="base">Vision Content</div>
<div class="vision hidden" id="highways">Vision Content2</div>
<div class="vision hidden" id="transport">Vision Content3</div>
</div>
<!-- The following function will run automatically when this script element
is reached. Always keep the script just before the closing body tag (</body>). -->
<script>
(function(){
// Get any/all slide-menu elements into an array
let menus =Array.prototype.slice.call(document.querySelectorAll(".slide-menu"));
// Loop over the menus
menus.forEach(function(menu){
// Loop over the list items in the menu
Array.prototype.slice.call(menu.querySelectorAll("li")).forEach(function(item, index){
let idx = index;
// Set up a click event handler for each item
item.addEventListener("click", function(){
// Get all the <div> items in this menu into an Array
let divs = Array.prototype.slice.call(menu.parentElement.querySelectorAll("div"));
// Hide any item that was previously showing
divs.forEach(function(div){ div.classList.add("hidden"); });
// Query the parent element (the container) for all the
// corresponding <div> items and make it visible
divs[idx].classList.remove("hidden");
});
});
});
}());
</script>
Can some one tell me, Why tag a make my first click without opening the table, but take the address which should go (in first moment table is hidden)
and after second click, table is opening and i'm going to it. without tag <a href="#team-#team.Id"> it open by 1 click. #team-**#team.Id** - it's normal, i did 15 tables by cycle, and make for each table id)
my code in view
<div id=team-logo-wrapper>
<ul>
#foreach (Team team in Model.Item2)
{
<li>
<div class="team-section-box">
<p class="team-name">#team.Name</p>
<a href="#team-#team.Id">
<img src="#Url.Content(string.Format("~/Images/NBAlogoImg/{0}", team.Path))" class="logo-images" alt="Логотип #team.Name" title="Логотип #team.Name" onclick="ShowTable(#team.Id)" />
</a>
</div>
</li>
}
</ul>
in CSS my display and visibility
.table-hidden {
margin-top: 50px;
display: none;
visibility: hidden;
}
the simplest script
var flag = true;
function ShowTable(teamId) {
var id = "team-" + teamId;
var getElem = document.getElementById(id);
if (flag) {
flag = false;
getElem.style.display = 'none';
getElem.style.visibility = 'hidden';
}
else {
flag = true;
getElem.style.display = 'block';
getElem.style.visibility = 'visible';
}
}
When you click on the image, you also activate the link.
If you really need the link, then change it to something like:
<a href="javascript: void(0)">
<img src="#Url.Content(string.Format("~/Images/NBAlogoImg/{0}", team.Path))"
class="logo-images" alt="Логотип #team.Name"
title="Логотип #team.Name"
onclick="ShowTable(#team.Id)" />
</a>
I have to toggle between two icons based on some criteria. How do I do this in jQuery?
<a href='' id="home" onclick="myfunction(this)" data-toggle="toggle">
<span class="fa fa-train"></span>
</a>
myfunction($this) {
// ...
if ($($this).hasClass("fa fa-train")) {
$($this).removeClass("fa fa-train");
$($this).addClass("fa fa-car");
}
else {
$($this).addClass("fa fa-car");
$($this).addClass("fa fa-train");
}
// ...
}
clicked anchor element do not have class added, its child span does :
function myfunction($this) {
$($this).find('span').toggleClass('fa-train fa-car');
}
Do something like this
$('a#home').on('click', function(){
var childSpan = $(this).find('span');
if(childSpan.hasClass('fa-train')){
childSpan.removeClass('fa-train');
childSpan.addClass('fa-car');
}
else if(childSpan.hasClass('fa-car')){
childSpan.removeClass('fa-car');
childSpan.addClass('fa-train');
}});
you are using this which will check the a tag if has class . while you should check in the span next to a tag .you should use like this
myfunction($this) {
// ...
if ($($this).next('span').hasClass("fa fa-train")) {
$($this).next('span').removeClass("fa fa-train");
$($this).next('span').addClass("fa fa-car");
}
else {
$($this).next('span').addClass("fa fa-car");
$($this).next('span').addClass("fa fa-train");
}
// ...
}
With a condition in one line:
$($this)
.addClass((condition=(Math.random() > .5)) ? 'fa-car' : 'fa-train')
.removeClass(condition ? 'fa-train': 'fa-car')
Note: This will not work if you "use strict" and of course your code will be less readable.
Thanks everyone, yes i had to search for 'span' and add toggle class. hasClass is also good way to check beforehand that the class exist or not.
This is a concept that I came with which is a bit logical. Instead of using complicated language, what this does is it hides the add button and makes a times button while showing the message that was hidden. It is fairly simple JQuery.
$(document).ready(function() {
$("#addCross").click(function() {
document.getElementById("addCross").style.display = "none";
document.getElementById("addAdd").style.display = "inline-block";
document.getElementById("hello").style.display = "block";
});
$("#addAdd").click(function() {
document.getElementById("addCross").style.display = "inline-block";
document.getElementById("addAdd").style.display = "none";
document.getElementById("hello").style.display = "none";
});
});
/*
Unoptional CSS
Just to make the buttons look better in the snippet.
*/
button {
background: transparent;
border: none;
}
button:focus {
outline: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://kit.fontawesome.com/9b271ce18a.js" crossorigin="anonymous"></script>
<div>
<label>Press the Button: </label>
<button id="addCross"><i class="fas fa-plus"></i>
<button id="addAdd" style="display: none;"><i class="fas fa-times"></i></button>
<div style="display: none;" id="hello">
<p>Hello. I was hidden by the Magic of JQuery.</p>
<label>This design also makes a cool rotating add sign if you look closely. Ha Ha!!</label>
</div>