javascript - How to run a .js file on multiple Bootstrap tabs? -
i have page runs javascript file pulls data json file. js appends div on page. js runs on $(document).ready.
i have added tabs page bootstrap, , run same js code on different tabs, accessing different json file each tab.
would need wrap js new function , call on function using tab click event? looking little on best way this.
edited add code:
<!doctype html> <html lang = "en"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- above 3 meta tags *must* come first in head; other head content must come *after* these tags --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script type="text/javascript" src="quiz.json"></script> <script src="quiz.js"></script> <link rel="stylesheet" type="text/css" href="assets/bootstrap-3.3.5-dist/css/bootstrap.min.css"> </head> <body role = "document"> <div class="container" > <div class="row"> <div class="col-md-12"> <h2>presidential trivia</h2> </hr> <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"><a href="#tab1" aria-controls="home" data-toggle="tab">home</a></li> <li role="presentation"><a href="#tab2" aria-controls="profile" data-toggle="tab">profile</a></li> <li role="presentation"><a href="#tab3" data-toggle="tab">messages</a></li> </ul> </div> </div> <!-- tab sections --> <div class="tab-content"> <div class="tab-pane active" id="tab1"> <div class="row" style="height:100px"> </div> <div class="row"> <div class="col-md-4"></div> <div class="col-md-4"> <div id='main' class="panel panel-info"> </div> <div class="progress"> <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" style="min-width:3%; width:0%"> </div> </div> <div id='buttons'> <button id='prev' class='btn'>back</button> <button id='next' class='btn pull-right'>next</button><br><br> <button id='restart' class='btn'>start over?</button> </div> </div> <div class="col-md-4"></div> </div> </div> <div class="tab-pane" id="tab2"> <div class="row" style="height:100px"> </div> <div class="row"> <div class="col-md-4"></div> <div class="col-md-4"> <div id='main' class="panel panel-info"> </div> <div class="progress"> <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" style="min-width:3%; width:0%"> </div> </div> <div id='buttons'> <button id='prev' class='btn'>back</button> <button id='next' class='btn pull-right'>next</button><br><br> <button id='restart' class='btn'>start over?</button> </div> </div> <div class="col-md-4"></div> </div> </div> </div> <div class="tab-pane" id="tab3">tab 3 content.... </div> </div> </div> <script src="assets/bootstrap-3.3.5-dist/js/bootstrap.min.js"></script> </body> </html>
javascript:
$(document).ready(function(){ var allquestions; var username ; var counter = 0; var main = $("#main"); var userinputs = []; var numcorrect = 0; var fadespeed = 700; var next = $("#next"); var prev = $("#prev"); var restart = $("#restart") //ajax call json file function getdata(myurl, cb) { $.ajax({ type: "get", url: myurl, success: function(content) { var mydata = content; cb(null, mydata); }, error: function() { cb(true); } }); } getdata('quiz.json', function(err, data) { if(err) { console.log('there error getting quiz data. try again later or contact admin.'); return; } //store data global variable allquestions = data; //load first question createqdiv(); }) if (counter == 0) { $("#prev").hide(); } //click handler next question button next.click(function() { var selection = $("input[name=answer]:checked").val(); if (selection != undefined) { choose(); fadequestion(); settimeout(function() { clearlast(); counter++; moveprogress(); prev.show(); createqdiv(); }, fadespeed); } else { alert("you must select answer proceed.") }; }); //creates question element function createqdiv() { //$("#prev").hide(); var question = $("<div id='question' class='panel-body'></div>").fadein(fadespeed); main.append(question); if (counter < allquestions.length) { displaynext(); } else { displayscore(); } }; //fade out question element function fadequestion() { $("#question").fadeout(fadespeed); }; //clears question element function clearlast() { main.empty(); }; //adds question , answers question element function displaynext() { restart.hide(); var qpara = $("<p>" + allquestions[counter].question + "</p>") $("#question").append(qpara); createradios(); addprevselection(); }; //creates radio buttons each choice function createradios() { var choices = allquestions[counter].choices; //var formelement = $("<form></form>"); //$("#question").append(formelement); (i = 0; < choices.length; i++) { $("#question").append($("<input type='radio' name='answer' value='" + + "'>" + choices[i] + "<br>")); }; }; //checks user's answer choice , stores in array function choose() { var input = $("input[name=answer]:checked").val(); userinputs[counter] = input; }; //create function checking user's answers vs number correct. output = number of correct answers function correctans() { (i = 0; < allquestions.length; i++) { if (userinputs[i] == allquestions[i].correct) { numcorrect++; }; }; }; //create 'last page' displaying user's score function displayscore() { next.hide(); prev.hide(); correctans(); var score = (numcorrect / allquestions.length); //var encouragement; var scoreelement = $("<p>you got " + numcorrect + " out of " + allquestions.length + " correct.</p>"); $("#question").append(scoreelement); /*if(score == 1){encouragement = " perfect score. amazing.";}else if(0.5<score<1){encouragement = "better luck next time!";}else{encouragement = "repeat after me: 'do want fries that?'"}; scoreelement.append(encouragement);*/ restart.show(); }; prev.click(function() { if (counter > 0) { fadequestion(); settimeout(function() { clearlast(); counter--; moveprogress(); createqdiv(); addprevselection(); choose(); }, fadespeed); //cristina: if user changes input , hits back? isn't kept, logged on next button. } else { prev.hide(); } }); function addprevselection() { var selection = userinputs[counter]; var radioselected = $("input[value='" + selection + "']"); //alert(radioselected); radioselected.prop("checked", true); }; restart.click(function() { counter = 0; next.show(); userinputs = []; numcorrect = 0; clearlast(); moveprogress(); createqdiv(); }); function moveprogress(){ var newwidth = ((counter)/allquestions.length)*100; $(".progress-bar").css("width", "" + newwidth + "%"); }; });
json file:
[{ "question": "how many presidents members of whig party?", "choices": ["four", "three", "two"], "correct": 0 }, { "question": "who first president impeached?", "choices": ["andrew jackson", "andrew johnson", "warren harding"], "correct": 1 }, { "question": "how many presidents died during presidency?", "choices": ["four", "six", "eight"], "correct": 2 }, { "question": "how many presidents had no party affiliation?", "choices": ["one", "two", "three"], "correct": 0 }, { "question": "who president serve 2 non-consecutive terms, making him both 22nd , 24th president?", "choices": ["john quincy adams", "william howard taft", "grover cleveland"], "correct": 2 }]
below demo on how can use 'show.bs.tab` event change content of current active pane before showing up. check inline comments more detailed explanation.
//below have given sample contents change dynamcically, can think //of changing or assigning urls here instead of contents //for ex: var url="sample/sample" , change in switch case var homejson="some home content"; var profilejson="some profile content"; var messagesjson="some message content"; var settingsjson="some settings content"; var body=""; function gettabcontents(target) { //based on target passed change url content in common function or //can pass url here based on tab selected , write ajax below /*$.ajax({ url:urlpassedasparameter, data:necessarydata, success:function(result){ return content here }, error:function(){ return message here } });*/ var content=""; switch(target){ case "home": content=homejson; break; case "profile": content=profilejson; break; case "messages": content=messagesjson; break; case "settings": content=settingsjson; break; default: break; } return content; } $(document).ready(function(){ //call function on document ready , pass first panel default body = gettabcontents("home") $('#home').html(body);//assign html of content changed particular tab-pane }); $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { //this method important , e.target below refers current element equal "this" var target=$(e.target).attr('aria-controls') // newly activated tab //fetch of data target element , use change url or content body=gettabcontents(target); //again contents function $("#"+target).html(body); //add html body. })
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <div> <!-- nav tabs --> <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">home</a></li> <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">profile</a></li> <li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">messages</a></li> <li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">settings</a></li> </ul> <!-- tab panes --> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="home">...</div> <div role="tabpanel" class="tab-pane" id="profile">...</div> <div role="tabpanel" class="tab-pane" id="messages">...</div> <div role="tabpanel" class="tab-pane" id="settings">...</div> </div> </div>
let me know if have doubts
Comments
Post a Comment