html - Not able to change div display property using javascript - Stack Overflow

I am trying to change display property of my div using js but it is not showing any change. In Js code

I am trying to change display property of my div using js but it is not showing any change.

In Js code if statements are not being true though in css all the properties are set properly. Please help I am a novice and not understanding the issue. Below is the code I am trying

My HTML Code:

<!DOCTYPE html>
<html>
<head>
<script src="main.js" type="text/JavaScript"></script>
</head>
<body>
 <nav id="nav">
      <ul class="main_nav">
    <li id="About_me"><a href="#" onclick="About_Me_Sel()">About Me</a></li>
    <li id="home1"><a href="#" onclick="Home_Sel()">Home</a></li>
</ul>
</nav>
<div id="About">
<p>Hello</p>
</div>
<div id="home">
<p>hi</p>
</div>
</body>

My JS code:

function About_Me_Sel()
{
    var Id;
    Id =document.getElementById("About");
    if(Id.style.display == "block")
    {
    Id.style.display = "none";
    }
}

function Home_Sel()
{
var Id;
Id= document.getElementById("home");

if(Id.style.display == "none")
{Id.style.display = "block";
}
else
alert("hello");
}

I am trying to change display property of my div using js but it is not showing any change.

In Js code if statements are not being true though in css all the properties are set properly. Please help I am a novice and not understanding the issue. Below is the code I am trying

My HTML Code:

<!DOCTYPE html>
<html>
<head>
<script src="main.js" type="text/JavaScript"></script>
</head>
<body>
 <nav id="nav">
      <ul class="main_nav">
    <li id="About_me"><a href="#" onclick="About_Me_Sel()">About Me</a></li>
    <li id="home1"><a href="#" onclick="Home_Sel()">Home</a></li>
</ul>
</nav>
<div id="About">
<p>Hello</p>
</div>
<div id="home">
<p>hi</p>
</div>
</body>

My JS code:

function About_Me_Sel()
{
    var Id;
    Id =document.getElementById("About");
    if(Id.style.display == "block")
    {
    Id.style.display = "none";
    }
}

function Home_Sel()
{
var Id;
Id= document.getElementById("home");

if(Id.style.display == "none")
{Id.style.display = "block";
}
else
alert("hello");
}
Share Improve this question edited Aug 20, 2013 at 21:29 Sanjana Porwal asked Aug 19, 2013 at 23:05 Sanjana PorwalSanjana Porwal 1551 gold badge2 silver badges6 bronze badges 1
  • You have two different elements with the id 'home' – Sterling Archer Commented Aug 19, 2013 at 23:15
Add a ment  | 

3 Answers 3

Reset to default 3

That won't work the first time around. The style property is not connected to your stylesheet, so JavaScript doesn't know what rule's you've set there. The style property reflects a style attribute that gets written into your element's tag. (You can hard-code one into your HTML if you want.) So the value is always null until you set it.

Before

<div id="About">

After

<div id="About" style="display: block">

Try reversing the conditional

if (Id.style.display != "block")
{
    Id.style.display = "block";
}
else
{
    Id.style.display = "none";
}

I used Ajax to load in other content into my div, and i got the content from other php files. this way

function changecontent(name){

var htmlUrl = name;
$.ajax({
    url: htmlUrl,
    dataType: 'html',
    success: function(data) {


        console.log("Current page is: " + htmlUrl);


        $("#maincontent").fadeOut(function() {
            $(this).html(data).fadeIn("fast");
        });
    }
  });
 }

HTML:

<!DOCTYPE html>
<html>
<head>
  <script src="main.js" type="text/JavaScript"></script>
   </head>
      <body>
         <nav id="nav">
          <ul class="main_nav">
            <li id="About_me"><a href="#" onclick="changecontent("about_me.php")">About Me</a></li>
            <li id="home"><a href="#" onclick="changecontent("home_sel.php")">Home</a></li>
          </ul>
         </nav>
         <div id="maincontent">
              <p>Hello</p>
         </div>
        <div id="home">
      <p>hi</p>
    </div>
  </body>

eks: about_me.php

<a>I'awesome</a>

You have a number of errors in your code; I'll try to go through them one-by-one to clarify those problems and offer solutions that should, hopefully, lead to better understanding (and practice) in future.

First, an id "...assigns a name to an element. This name must be unique in a document."1. Note the 'must,' which means that a document with a duplicated id (more than one element sharing the same id value makes the document invalid, and causes problems with JavaScript, since it will only ever look for one element with a given id, and recover from invalid documents with unpredictable results).

That being the case I've amended the ids of the div elements by, effectively, adding the Content string, and amended the ids of the li elements to be single word and lower-case so that they can be predictably made to reference each other. This gives the following HTML:

<nav id="nav">
    <ul class="main_nav">
        <li id="about"><a href="#" onclick="About_Me_Sel()">About Me</a></li>
        <li id="home"><a href="#" onclick="Home_Sel()">Home</a></li>
    </ul>
</nav>
<div id="aboutContent">
    <p>Hello</p>
</div>
<div id="homeContent">
    <p>hi</p>
</div>

JS Fiddle (this still doesn't work as you'd intend, because the other problems still exist; it's merely to show the corrected/amended HTML).

Now, the JavaScript.

The reason it can't work, as noted by @Jeffman in his answer is because element.style references only the in-line styles of an element (those set with the style attribute), not the styles set with either a stylesheet or in the head of the document. This means you're paring an undefined variable with a string, which will always be false.

You're also using two functions to do the same thing, which is wasteful and unnecessary. This is the second reason I've modified the ids of the various elements. A modified (single) function to do what you want to do:

function sel(e, self) {
    // e is the click event,
    // self is the 'this' DOM node
    var id = self.parentNode.id,
        toggle = document.getElementById(id + 'Content'),
        display = toggle.style.display;
    toggle.style.display = display == 'block' ? 'none' : 'block';
}

The above requires the following HTML for the a elements:

<a href="#" onclick="sel(event, this)">About Me</a>

JS Fiddle demo.

Now, this still requires obtrusive JavaScript (using in-line event-handling within the HTML itself, which requires updates every time you may want to add further event-handling or change the function to call upon those events). Therefore I'd suggest moving to a more unobtrusive version, such as:

function sel(e, self) {
    // e is the click event,
    // self is the 'this' DOM node
    var id = self.parentNode.id,
        toggle = document.getElementById(id + 'Content'),
        display = toggle.style.display;
    toggle.style.display = display == 'block' ? 'none' : 'block';
}

var links = document.getElementById('nav').getElementsByTagName('a');

for (var i = 0, len = links.length; i < len; i++) {
    links[i].onclick = function (e){
        sel(e, this);
    };
}

JS Fiddle demo.

Now, while this works, this still requires assigning event-handlers to multiple elements (despite being more easily done using a loop within JavaScript itself).

The easier way is to delegate the event-handling to the parent element, and assess, in the function itself, where the event originated. Which would give the following JavaScript:

function sel(e) {
    // e is the click event,
    // self is the 'this' DOM node
    var self = e.target,
        id = self.parentNode.id,
        toggle = document.getElementById(id + 'Content'),
        display = toggle.style.display;
    toggle.style.display = display == 'block' ? 'none' : 'block';
}

var nav = document.getElementById('nav');
nav.addEventListener('click', sel);

JS Fiddle demo.


Notes:

  1. http://www.w3/TR/html401/struct/global.html#h-7.5.2.

References:

  • addEventListener().
  • document.getElementById().
  • getElementsByTagName().
  • Node.parentNode.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744689563a4588127.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信