Jump to content
  • Announcements

    • boen_robot

      Guidelines and Netiquette   03/28/2017

      Posting Problems:   Having problems posting your topic? Read through this: To join, you agree to our terms and conditions and fill out and submit a registration form. An activation email will be sent to your email adress, so you'll need to verify your account. After that the account has to be validated by one of the moderators. This will mean that it can take up to a day to be activated. A couple of things to remember to ensure approval: Don't use an email address in one of those $2 four character .com domains eg. xyds.com. These will be deleted and the domain added to the banned list. Don't use an email address that is within a domain with a bad reputation for spam. A Google search is run on every email address and email domain. Don't sign up with an email address that doesn't exist, doesn't work or requires the sender to answer a quiz before their email can get to you. Put your country and or state and city in the signup form. Blank forms will go to the botton of the "to do" list. And make sure that your email address and your country match, saying you're from Alabama and using a .ru email address is not going to get you activated. After a membership is activated the first few posts will be monitored. Posting spam or unapproved topics described in the agreement results in an immediate ban. The email provider and the IP addresses associated with the account will be banned and all posts will be deleted. These strict measures have been deemed necessary to hinder spam. Sorry for any inconvenience this causes, but it's not liable to change. If, after reading this, you still can't post and don't understand why, contact one of the Moderators listed here.   Topic Guidelines   Including the following information can expedite an accurate response from board members: Must be a Specific Problem or Question related to web design and development Include Code in Question (wrap with   for small blocks of code and for longer blocks   ) Include Code Author Include Extra Notes/Modifications/Attempts Include web link to page/file when possible Content Guidelines   You may not post, upload, link to, or email any Content that contains, promotes, gives instruction about, or provides prohibited Content. Prohibited Content includes any Content that breaks any local, state, county, national or international law. Prohibited Content also includes: No direct or indirect advertising or websites, forums, products, services No hijacking of posts (do not post your question in someone elses) Content that infringes upon any rights [ex. MP3s and ROMs] (including, but not limited to, copyrights and trademarks) Abusive, threatening, defamatory, racist, or obscene Viruses or any other harmful computer software False Information or libel Spam, chain letters, or Pyramid schemes Gambling or Illicit drugs Terrorism Hacking or cheating for internet/online games Warez, Roms, CD-Keys, Cracks, Passwords, or Serial Numbers Pornography, nudity, or sexual material of any kind Excessive profanity Invasive of privacy or impersonation of any person/entity Hacking materials or information Posting Tips   There are more BBcodes than there are buttons for on the reply menu. To get the full list, click "BB Code Help" underneath the clickable smilie face menu. Use   for small snippets of code Use   for lengthy snippets of code Use   if your snippet is HTML (optional) Use   if your snippet is SQL (optional) Rules of Conduct   Be nice. There's no need for calling someone stupid if they ask an 'easy' question. Keep your avatars and signatures absolutely child friendly. We have a younger audience on this forum. Keep your language appropriate for the same reason above. Do not PM moderators for help on the forum. Post on the topic, or create a new one.   Spam:   Recently, as you have all without doubt noticed, we have had lots of spam and advertisement on the forum. Therefore, we'd like to alert you as to what to do when you have found any of the aforementioned annoying messages: it. Immediately. Give a clear reason, please, if the advertising is not evident. DO NOT POST! Report, let the post stay as is, and we will get to it, meanwhile if you continue to post as normal in the other threads, it won't be on the top so long. Refrain from PMing the member. This won't help at all, as they are most likely spambots anyway. Thank you.       Images in signatures:   After thinking of users on dial-up, we have decided to enforce the following rules regarding signatures. Please pay heed to them. Respecting these rules is respecting the members on this forum with dial-up. Signature rules: No animated images AT ALL. No matter the amount of animation. Maximum image widthxheight: 300x150 Maximum image (file) size: 15kb Use calm colors. Do not use highly contrasting images in your signature, as this can get really annoying when seeing several posts from one member in the same thread. The same prohibited content goes for images as for posts. Lastly, use common sense. No lengthy signatures please. Save us some scrolling. Thank you.       Links in signatures:   Please understand that w3schools.com only exists because of voluntary work and is barely supported by the advertising littered throughout the tutorials and the forum. So, please, stop advertising other sites. DO not post links that drive traffic away from the w3schools domain - especially to a site that offers similar if not identical information. Please help support the site by keeping individuals on it. Thank you. Here are some guidelines as to what you can put in your signature: w3schools links --> allowed w3.org links --> allowed browser links --> allowed html editor links --> allowed personal sites --> allowed tutorial sites competing with w3schools --> NOT allowed sites completely irrelevant to webprogramming and this forum --> NOT allowed   Thanks for understanding, and for taking the time to read this. ~W3Schools Modstaff~
ahile91

How i use this script for 2 functions same works

Recommended Posts

ahile91    0
<!DOCTYPE html>
<html>
<head>
<style>
.container {
    overflow: hidden;
    background-color: #333;
    font-family: Arial;
}

.container a {
    float: left;
    font-size: 16px;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

.dropdown {
    float: left;
    overflow: hidden;
}

.dropdown .dropbtn {
    cursor: pointer;
    font-size: 16px;    
    border: none;
    outline: none;
    color: white;
    padding: 14px 16px;
    background-color: inherit;
}

.container a:hover, .dropdown:hover .dropbtn {
    background-color: red;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.dropdown-content a {
    float: none;
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {
    background-color: #ddd;
}

.show {
    display: block;
}
</style>
</head>
<body>

<div class="container">
  <a href="#home">Home</a>
  <a href="#news">News</a>
  <div class="dropdown">
    <button class="dropbtn" onclick="myFunction()">Dropdown</button>
    <div class="dropdown-content" id="myDropdown">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </div> 
</div>

<h3>Dropdown Menu inside a Navigation Bar</h3>
<p>Click on the "Dropdown" link to see the dropdown menu.</p>

<script>
/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
  if (!e.target.matches('.dropbtn')) {
    var myDropdown = document.getElementById("myDropdown");
      if (myDropdown.classList.contains('show')) {
        myDropdown.classList.remove('show');
      }
  }
}
</script>
</body>
</html>

 

 

i just tryit by myself to change from "myDropdown" to "myDropdown_2" but it wasan't work...i just want to add this to my categories so i want to multiplay this content like 2-3 times how do i make this ? please help

Share this post


Link to post
Share on other sites
davej    244

Try experimenting with this and you will see the problem...

window.onclick = function(e) {
  if (!e.target.matches('.dropbtn')) {
  alert('try to remove show from myDropdown');
    var myDropdown = document.getElementById("myDropdown");
      if (myDropdown.classList.contains('show')) {
        myDropdown.classList.remove('show');
      }
  }else{
    alert('ignore');
  }
}

 

Share this post


Link to post
Share on other sites
ahile91    0

i tryed before posting..is work for one only<script>

/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("myDropdown_2").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
  if (!e.target.matches('.dropbtn_2')) {
    var myDropdown_2 = document.getElementById("myDropdown_2");
      if (myDropdown_2.classList.contains('show')) {
        myDropdown_2.classList.remove('show');
      }
  }
}
</script>

 

Share this post


Link to post
Share on other sites
ahile91    0
Just now, ahile91 said:

i tryed before posting..is work for one only<script>


<script>
/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("myDropdown_2").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
  if (!e.target.matches('.dropbtn_2')) {
    var myDropdown_2 = document.getElementById("myDropdown_2");
      if (myDropdown_2.classList.contains('show')) {
        myDropdown_2.classList.remove('show');
      }
  }
}
</script>

 

 

Share this post


Link to post
Share on other sites
justsomeguy    936

You should show all of your code, your attempt to make it work.  Are you trying to use the name myFunction for more than function, for example?  Are you overwriting window.onclick?  I can't tell from what you're showing.  Show your complete attempt.

Share this post


Link to post
Share on other sites
dsonesuk    701

The problem is you are using getElementById(), which is singular, when you should target specific classnames which are multiple, by targeting classnames you use 'this' to transverse down to specfic element that you can toggle class 'show' and 'hide' with.

Share this post


Link to post
Share on other sites
ahile91    0

ok i'm confuse now idk how to make it...so this is the code..let me explain better. first i want to make "rental" and "cars" to dropdown and the dropdown content (submenu) style it to put it in a box container. all this in the header than under to put some slideshow and 6/8 col photo gallery. i'm using 16grid from 960

<!DOCTYPE html>
<html lang="en-US">
<head>
	<title>title</title>
<meta name="keywords" content="bla bla">
<meta name="description" content="about bla bla">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" type="text/css" href="style.css">
	<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source Serif Pro">
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
 <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<![endif]-->
</head>
<!-- body -->
<body>
	<div class="container_16">
<style>
body,h1,h2,h3,h4,h5,h6 {font-family: "Source Serif Pro", sans-serif}
</style>
<!-- header -->
<header>
	<div class="grid_5 alpha brand">webname</div>
	<div class="grid_11 omega">
<!-- navigation -->
		<nav>
			<ul>
				<li><a href="#">Contact</a> |</li>
				<li><a href="#">Home</a> |</li>
				<li><a href="#">SingUp</a></li>
			</ul>
		</nav>
	</div>
	<div class="grid_5">
	<div class="dropdown_1">
  <button onclick="myFunction()" class="dropbtn_1">Rental</button>
  <div id="myDropdown_1" class="dropdown-content_1">
			<a href="#">House</a>
			<a href="#">Studio</a>
			<a href="#">Flat</a>
	</div>
	</div>
	</div>
	<div class="grid_5">
	<div class="dropdown_2">
  <button onclick="myFunction()" class="dropbtn_2">Cars</button>
  <div id="myDropdown_2" class="dropdown-content_2">
			<a href="#">Electric</a>
			<a href="#">Petrol</a>
			<a href="#">Diesel</a>
	</div>
	</div>
	</div>
</header>
<!-- footer -->
<footer>
	<p>&copy; 2017 All rights reserved.</p>
</footer>
<!-- navigation java script -->
<script>
/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("myDropdown_1").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
  if (!e.target.matches('.dropbtn_1')) {
    var myDropdown_1 = document.getElementById("myDropdown_1");
      if (myDropdown_1.classList.contains('show')) {
        myDropdown_1.classList.remove('show');
      }
  }
}
</script>
<script>
/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("myDropdown_2").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
  if (!e.target.matches('.dropbtn_2')) {
    var myDropdown_2 = document.getElementById("myDropdown_2");
      if (myDropdown_2.classList.contains('show')) {
        myDropdown_2.classList.remove('show');
      }
  }
}
</script>
</body>
</html>

 

Edited by ahile91

Share this post


Link to post
Share on other sites
dsonesuk    701

Lose the id ref on on div its obsolete for this, all you need is for example is

            <div class="dropdown">
                <button class="dropbtn" onclick="myFunction(this)">Dropdown</button>
                <div class="dropdown-content">
                    <a href="#">Link 1</a>
                    <a href="#">Link 2</a>
                    <a href="#">Link 3</a>
                </div>
            </div>
            <div class="dropdown">
                <button class="dropbtn" onclick="myFunction(this)">Dropdown #2</button>
                <div class="dropdown-content">
                    <a href="#">Link 2#1</a>
                    <a href="#">Link 2#2</a>
                    <a href="#">Link 2#3</a>
                </div>
            </div>

When you click the button it pass with 'this parameter to identify which element the event came from.

Then you tell it to move to next sibling element which will be the div cont element with this

            function myFunction(elem) {
                elem.nextElementSibling.classList.toggle("show");

            }

And toggle 'show' class.

Now for window onclick event, you loop through all 'dropdown-content' and if classList includes 'show' you remove it

            window.onclick = function(e) {
                if (!e.target.matches('.dropbtn')) {
                    var myDropdown = document.getElementsByClassName("dropdown-content");

                    for (var i = 0; i < myDropdown.length; i++) {
                        if (myDropdown[i].classList.contains('show')) {
                            myDropdown[i].classList.remove('show');
                        }
                    }
                }
            };

 

Share this post


Link to post
Share on other sites
ahile91    0
<!DOCTYPE html>
<html lang="en-US">
<head>
	<title>title</title>
<meta name="keywords" content="bla bla">
<meta name="description" content="about bla bla">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" type="text/css" href="style.css">
	<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source Serif Pro">
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
 <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<![endif]-->
</head>
<!-- body -->
<body>
	<div class="container_16">
<style>
body,h1,h2,h3,h4,h5,h6 {font-family: "Source Serif Pro", sans-serif}
</style>
<!-- header -->
<header>
	<div class="grid_5 alpha brand">webname</div>
	<div class="grid_11 omega">
<!-- navigation -->
		<nav>
			<ul>
				<li><a href="#">Contact</a> |</li>
				<li><a href="#">Home</a> |</li>
				<li><a href="#">SingUp</a></li>
			</ul>
		</nav>
	</div>
	<div class="grid_5">
	<div class="dropdown">
  <button onclick="myFunction(elem)" class="dropbtn">Rental</button>
  <div class="dropdown-content">
			<a href="#">House</a>
			<a href="#">Studio</a>
			<a href="#">Flat</a>
	</div>
	</div>
	</div>
	<div class="grid_5">
	<div class="dropdown_2">
  <button onclick="myFunction()" class="dropbtn_2">Cars</button>
  <div class="dropdown-content_2">
			<a href="#">Electric</a>
			<a href="#">Petrol</a>
			<a href="#">Diesel</a>
	</div>
	</div>
	</div>
</header>
<!-- footer -->
<footer>
	<p>&copy; 2017 All rights reserved.</p>
</footer>
<!-- navigation java script -->
<script>
/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function myFunction(elem) {
                elem.nextElementSibling.classList.toggle("show");

            }

// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
                if (!e.target.matches('.dropbtn')) {
                    var myDropdown = document.getElementsByClassName("dropdown-content");

                    for (var i = 0; i < myDropdown.length; i++) {
                        if (myDropdown[i].classList.contains('show')) {
                            myDropdown[i].classList.remove('show');
                        }
                    }
                }
            };
</script>
<script>
/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("myDropdown_2").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
  if (!e.target.matches('.dropbtn_2')) {
    var myDropdown_2 = document.getElementById("myDropdown_2");
      if (myDropdown_2.classList.contains('show')) {
        myDropdown_2.classList.remove('show');
      }
  }
}
</script>
</body>
</html>

 

Share this post


Link to post
Share on other sites
dsonesuk    701

TUT, tut

ALL

<button onclick="myFunction(elem)" class="dropbtn">....</button>

should be (very important to have exact class name shown and onclick="myFunction(this)")

<button onclick="myFunction(this)" class="dropbtn">....</button>

ALL opening divs following above should be

<div class="dropdown-content">

Finally! get rid of this (at the bottom)

<script>
/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("myDropdown_2").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
  if (!e.target.matches('.dropbtn_2')) {
    var myDropdown_2 = document.getElementById("myDropdown_2");
      if (myDropdown_2.classList.contains('show')) {
        myDropdown_2.classList.remove('show');
      }
  }
}
</script>

 

Edited by dsonesuk

Share this post


Link to post
Share on other sites
ahile91    0

yeah ! not is working for bouth but why when i open bouth is stay opens bout of them why is not closeing one ? btw your the best ! thanks so much !

and how is posible cuz in my head is not matching "this" with "elem"

Quote


<button onclick="myFunction(this)" class="dropbtn">....</button>

function myFunction(elem) {
                elem.nextElementSibling.classList.toggle("show");

            }


and this "e" is same "elem" ? just shortcut ?

window.onclick = function(e) {
                if (!e.target.matches('.dropbtn')) {
                    var myDropdown = document.getElementsByClassName("dropdown-content");

                    for (var i = 0; i < myDropdown.length; i++) {
                        if (myDropdown[i].classList.contains('show')) {
                            myDropdown[i].classList.remove('show');
                        }
                    }
                }
            };

 

 

Share this post


Link to post
Share on other sites
dsonesuk    701

'this' is JavaScript ref to element that triggered event, 'elem' can be called whatever you want within reason NOT 'this', it still refers to element that triggered event.

'e' is shortcut and represents an event that was triggered, totally different from 'this'.

To have one open at a time means you have to loop through all but current and close, similar script of for loop in window.onclick event.

Share this post


Link to post
Share on other sites
ahile91    0

can you writhe it for me please? after i get good knowlage of html and css i'll start studyng java and php..you want to hear something funny ? i not even finish the high school but i'm trying to build my own website and start a busines with it. i think i pasion can beat some mistake that i make them when i was younger

Share this post


Link to post
Share on other sites
justsomeguy    936

Since it wasn't clearly stated, you just copied and pasted the Javascript code twice.  You used the same function name, and you overwrote window.onclick.  The second time you define myFunction, it removes the first one (or it causes a fatal error, I'm not sure which in this case).  And the second time you assign a function to window.onclick, you remove the first function that you assigned to it.  You need to name things differently, names in Javascript are unique.  You can't name 10 things the same thing and expect to be able to refer to all of them at the same time.  And if you need multiple things to happen when an event happens, like window.onclick, then you need to combine that instead of replacing one with the other.  This is one way to do that:

old_onclick = window.onclick; // save the old function
	window.onclick = function() {
	  old_onclick(); // run the old handler
	  // then do new stuff
	}

The more modern way is to use window.addEventListener to add a new event handler instead of changing things like window.onclick.

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

 

Share this post


Link to post
Share on other sites
ahile91    0

now i just write that and u say now is an easy way ? hehhe is very dificult this java script 

i'm going to sleep now is 2:30am so tomorrow i'll see what i do...

Edited by ahile91

Share this post


Link to post
Share on other sites
dsonesuk    701
            function myFunction(elem) {
                elem.nextElementSibling.classList.toggle("show");
                var myDropdown = document.getElementsByClassName("dropdown-content");
                for (var i = 0; i < myDropdown.length; i++) {
                    if (myDropdown[i].classList.contains('show')) {
                        if (elem.nextElementSibling !== myDropdown[i]) {
                            myDropdown[i].classList.remove('show');
                        }
                    }
                }
            }

BUT! you do realise, the window onclick example (https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_js_dropdown) does not work in MS Edge, its so good of w3schools to give you an example that does not work in MS Edge and not tell you.

  • Like 1

Share this post


Link to post
Share on other sites
dsonesuk    701

Here's the fix for MS kak, you would have thought they would have known better by now.

            // Close the dropdown if the user clicks outside of it
            window.onclick = function(e) {
/*because of MS god complex thou shall do it how I WANT, and not how every else wants, 
which I thought they had finally begun to see the light, but apparently not! we have to allow for MS kak way of doing things*/ 
                matches = e.target.matches ? e.target.matches('.dropbtn') : e.target.msMatchesSelector('.dropbtn'); 
                if (!matches) {
                    var myDropdown = document.getElementsByClassName("dropdown-content");

                    for (var i = 0; i < myDropdown.length; i++) {
                        if (myDropdown[i].classList.contains('show')) {
                            myDropdown[i].classList.remove('show');
                        }
                    }
                }
            };

 

  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×