Skip to content Skip to sidebar Skip to footer

Show/hide Div Using Javascript Without Page Refresh

I have a script that shows /hides multiple independent divs on a page. The problem is that when you click to show a div, no matter where on the page, it will automatically focus on

Solution 1:

Give your show links a class, like:

<aclass="show"href="#"onclick="toggleOptions(this);"style="display:block;">show</a>

Then add this to your jQuery:

$('a.show').click(function(e){
    e.preventDefault();
});

The default action for a bookmark anchor (href="#") is to jump to the top of the page. This would prevent that. jsFiddle example

An alternative, jQuery-less method would be to change your onclicks to:

onclick="return toggleOptions(this);"

As you are already returning false. jsFiddle example

Solution 2:

I believe you could also use the .focus() method to focus on a given element. In your example:

functiontoggleOptions(e) {
    var ele = e;
    var text = e.parentElement.querySelector('.toggleOptions')

    if(text.style.display == "none") {
        //ele.style.display = "none";
        text.style.display = "block";
        text.innerHTML = "TESTING";
        text.focus(); //This should give focus to the newly shown text element
        ele.innerHTML = "hide";
    }
    else {
        text.style.display = "none";
        //text.innerHTML = "Hide GPS";
        ele.innerHTML = "show";
    }

    returnfalse;
}

Unless I am misunderstanding what you are looking to do....

Solution 3:

use javascript:void(0) in href. Use javascript functions to show or hide using id

<ahref="javascript:void(0)">Show</a>

Post a Comment for "Show/hide Div Using Javascript Without Page Refresh"