简体   繁体   中英

How to make this JavaScript function fade in or out?

I have a JavaScript function that creates a DOM node and inserts a question:

function setHeader(){
    var questionBox = document.createElement("div");
    questionBox.setAttribute("id","question" + (questionNumber + 1));
    document.body.insertBefore(questionBox,scriptBox);
    var questionElement = document.createElement("h3");
    questionElement.setAttribute("id","question" + (questionNumber + 1));
    var questionText = document.createTextNode(questions[questionNumber].question);
    questionElement.appendChild(questionText);
    questionBox.appendChild(questionElement);
}

What I would like to know is how can I make the question fade in or out using jQuery?

The above function creates:

<div id="question1">
   <h3 id="question1">Question here</h3>
</div>

I just realised I have the same ID for the div and h3

Try (it uses jQuery since you have tagged it using jQuery)

function setHeader() {
    var questionBox = document.createElement("div");
    questionBox.setAttribute("id", "question" + (questionNumber + 1));
    var questionElement = document.createElement("h3");
    questionElement.setAttribute("id", "question" + (questionNumber + 1));
    var questionText = document.createTextNode(questions[questionNumber].question);
    questionElement.appendChild(questionText);
    questionBox.appendChild(questionElement);

    //adding to the current dom with fade In animation
    //for the fadeIn to work first the element must be hidden so we hide the target element first then adds it to the dom after that the fadeIn() animation method is called
    $(questionBox).hide().appendTo(scriptBox).fadeIn()
}

Demo: Fiddle

Jquery provides fade in and fade out functions.

$('h3#question'+(questionNumber+1)).fadeIn();
$('h3#question'+(questionNumber+1)).fadeOut();

as a sidenote, ID attributes should be unique within a document. The above code should work regardless, but having duplicate ID's may give you headaches down the road.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM