Domanda

I have not found neither a direct nor general answer to this problem but I believe there might be a general interest in solving it once and for all. I must admit I'm quite new to js.

My problem is, that I need to click twice on "link" to execute the javascript.

head:

<script type="text/javascript">
function toggle(navi){
var elem = document.getElementById(navi);

if(elem.style.top == "-604px"){
    elem.style.top = "0px"; // elem.style.textDecoration = "underline"; 
}else{
    elem.style.top = "-604px";//elem.style.textDecoration = "none";
}}
</script>

body

<a href="javascript:toggle('navi')">Link</a>

A fiddle for better understanding: fiddle

Maybe you can help me out..

È stato utile?

Soluzione

Firstly you were not passing a string into the 'toggle' function for it to select the element by it's id.

Then getting the CSS 'top' property using JQuery seems to solve the issue of 'elem.style.top' being empty on initialisation (requiring double click).

Here's the working fiddle: http://jsfiddle.net/gkhBM/

$("#clicketyclick").click(function() { toggle("navi"); });

function toggle(navi) {
    var elem = document.getElementById(navi);
    //console.log(elem.style.top);
    //console.log($(elem).css('top'));
    if($(elem).css('top') == "-604px"){
        $(elem).css('top',"0px"); // elem.style.textDecoration = "underline"; 
    }else{
        $(elem).css('top',"-604px");//elem.style.textDecoration = "none";
    }
}

console.log is extremely useful when debugging problems.

Altri suggerimenti

you might want to do this using jQuery, then you only have to click once:

<a id='clicketyclick'>Link</a>

<script>
    $("#clicketyclick").click(function() {
        toggle(navi);
    });
</script>

If you're new to JS you should learn jQuery, since it is one of the best javascript frameworks around, and it will make your life quite a lot easier.

If you,however, don't want to use jQuery, you could basically use:

<a onclick="toggle(navi)">Link</a>

You could do as Max Langarek says or you could also just but click as a button instead of an a tag.

Maybe something like

<button  onclick="toggle(navi)">Button</button>

Either way, I've not seen the javascript:toggle(navi) way of calling a function before.. maybe I need more experience.

Try counting your clicks

var clickNumber = 1;

function functionTwice() {

    if(clickNumber == 1) {
        clickNumber = clickNumber +1;
    }
    else if(clickNumber == 2) {
        clickNumber = 1;
            var elem = document.getElementById(navi);

    if(elem.style.top == "-604px"){
        elem.style.top = "0px"; // elem.style.textDecoration = "underline"; 
    }else{
        elem.style.top = "-604px";//elem.style.textDecoration = "none";
    }
    }


}

HTML:

<a id='clicketyclick' onClick="functionTwice()">Link</a>
<div id="navi"></div>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top