Getting Javascript True/False quiz to work on WordPress site

I am in the process of converting a static HTML site to WordPress for a client. On their existing site they have this quiz http://www.virginiauranium.com/quiz . I have copied everything from their original site over to the WordPress installation, but as you will see as you answer questions, after question 2 it kicks you back to the first question http://www.virginiauranium.com/wp/quiz/

I am completely stumped by this and hope someone here can give me some guidance. I will include all related code.

Read More

The template:

<?php
require_once( ABSPATH . 'wp-content/themes/virginiauranium/includes/quiz.questions.php');

$question = $questions[$currQuestion-1];
?>

<div id="body" class="quiz">
    <h1>Uranium 101 <em>Would you pass? Take the quiz!</em></h1>
    <hr />

    <div class="quiz_header">
        <?php if($currQuestion == sizeof($questions)) { ?>
            <h4>Final Score: <?=$numCorrect?> out of <?=sizeof($questions)-1?></h4>
        <?php } else { ?>
            <h4>Question <?=$currQuestion?> of <?=sizeof($questions)-1?></h4>
            <a href="http://www.virginiauranium.com/wp/quiz" class="quiz_next">Next</a>
        <?php } ?>
    </div>

    <div class="quiz_body">
        <?php if($question['image'] != "") { ?>
        <p class="alignright<?=(($currQuestion == 7) ? " nomargin" : "")?>">
            <img src="<?php bloginfo('stylesheet_directory'); ?>/images/quiz/<?=$question['image']?>" alt="" /><br />
            <span class="caption"><?=$question['caption']?></span>
        </p>
        <?php } ?>

        <div class="question"><?=$question['question']?></div>

        <?php if($currQuestion < sizeof($questions)) { ?>
        <div class="quiz_buttons">
            <a href="javascript:void(0);" class="quiz_button_true">True</a>
            <a href="javascript:void(0);" class="quiz_button_false">False</a>
        </div>

        <div class="answer">
            <p><strong><?=ucfirst($question['shortanswer'])?>.</strong></p>
            <p><?=$question['answer']?></p>
            <span class="hide"><?=$question['shortanswer']?></span>
        </div>
        <?php } ?>
    </div>
    <input type="hidden" name="currentQuestion" value="<?=$currQuestion?>">
</div>
    </div><!-- #main .wrapper -->
    <footer id="colophon" role="contentinfo">
        <div class="site-info">
            <p>Virginia Uranium, Inc., P.O. Box 399, 231 Woodlawn Heights, Chatham, VA 24531 USA. Tel: 434.432.1065 Copyright &copy; <?php echo the_date('Y'); ?> Virginia Uranium, Inc. All rights reserved.</p>
        </div><!-- .site-info -->
    </footer><!-- #colophon -->
</div><!-- #page -->
<?php wp_reset_query(); ?>
<?php wp_footer(); ?>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="<?php bloginfo('stylesheet_directory'); ?>/js/jquery.cycle.js"></script>
<script type="text/javascript" src="<?php bloginfo('stylesheet_directory'); ?>/js/sitenew.js"></script>
</body>
</html>

quiz.questions.php

<?php
$questions = array(
    array(
        "question" => "Uranium is a common element which occurs in the soil of most backyards, most rocks, and seawater.", 
        "answer" => "Uranium is found nearly everywhere in small concentrations. Although used primarily as fuel for nuclear power plants, uranium is also used for weights in airplanes, military armor, and various advanced medical procedures and treatments.", 
        "shortanswer" => "true", 
        "image" => "Q1---core-samples.jpg",
        "caption" => "Ore samples from Coles Hill"
    ), array(
        "question" => "It is standard practice to install waste-water treatment plants at uranium mines and mills today.", 
        "answer" => "If Virginia Uranium’s enterprise moves forward, the company will build a wastewater treatment plant at the mine/mill site.  Water used in the mill process will be recycled and re-used in the mill process. Any water used or collected on site will be cleaned to standards set by the Environmental Protection Agency before it is released on site.  The treatment plant will be capable of cleaning water to E.P.A. drinking-water standards.", 
        "shortanswer" => "true", 
        "image" => "Q2---Ranger2005.jpg",
        "caption" => "Key Lake uranium facility, Canada"
    ), array(
        "question" => "Tailings are a radioactive waste product from mining.", 
        "answer" => 'Actually, "tailings" is the term for the crushed rock that remains once the uranium has been removed from the ore in the milling process. The uranium is separated out by a heated sodium bicarbonate leach (basically soda water). The ore at Coles Hill is unique from other uranium ores from the Western U.S or Canada in that it does NOT contain significant quantities of heavy metals or sulfides, which could be of environmental concern.  Yes, there is some radioactivity, but is it important to note that the tailings are less radioactive than the naturally occurring rock in the ore deposit.  Industry best practices recommend the addition of a binding agent to the tailings so that they will harden back into solid rock once they are placed into a below-grade tailings containment structure. The addition of a binding agent and the placement below grade remove any risk that the tailings could be swept away in a flood or hurricane and affect water quality.', 
        "shortanswer" => "true", 
        "image" => "Q3---tailings-pic.jpg",
        "caption" => "Tailings management facilities at JEB mine, Canada"
    ), array(
        "question" => "A mining operation at Coles Hill would pollute the air for miles.", 
        "answer" => "Water is used in the mining and milling process to keep down the dispersion of dust.  Moreover, Virginia Uranium’s plan to build an underground mine would eliminate dust emissions outside of the Coles Hill property, and tailings, the crushed rock from which the uranium is removed, are stored as a heavy liquid slurry under water.  They are not susceptible to wind dispersion.  While radon gas is associated with uranium, improved ventilation practices have minimized worker exposure to radon gas over the past forty years.  In fact, according to Canadian regulators, many uranium miners in Saskatchewan, Canada, receive more radon exposure in their homes than in the mines.", 
        "shortanswer" => "false", 
        "image" => "Q4---air-quality.jpg",
        "caption" => ""
    ), array(
        "question" => "Radiation from uranium mines and mills has not increased the cancer rates of communities living near mines and mills.", 
        "answer" => "Highly-respected studies confirm that cancer rates of communities living in the vicinity of uranium mining operations are no higher than those of the general population. Dr. John Boice, an epidemiologist from Vanderbilt University’s School of Medicine, studied four populations who lived near uranium mines in the western United States for decades and found no increased rates of cancer.", 
        "shortanswer" => "true", 
        "image" => "Q4---Gartempe-River-2.jpg",
        "caption" => ""
    ), array(
        "question" => "The drastic changes in the spot-market price of uranium will subject Virginia Uranium to boom-and-bust cycles.", 
        "answer" => "Most uranium is sold under long-term price contracts between mining companies and utilities such as Dominion Power.  Contracts lasting up to twenty years are conceivable.  Only about 25% of global uranium mine production is sold on the spot market, because it is in the best interest of utilities to ensure a stable supply of uranium to power their reactors. Long-term supply contracts benefit uranium mining companies by ensuring a stable uranium selling price for long periods of time.", 
        "shortanswer" => "false", 
        "image" => "Q6---surry-reactors.jpg",
        "caption" => "Nuclear reactors at Surry Power Station, Virginia"
    ), array(
        "question" => "Virginia Uranium could draw all the water it would need to operate a uranium mine and mill at Coles Hill from its site.", 
        "answer" => "Virginia Uranium would require approximately 300,000 gallons of water per day, all of which would come from the 3,500-acre Coles Hill site.  That sounds like a lot of water, but it is slightly less than the Town of Chatham, a nearby town of 1,200 residents, uses. It is far less than other industrial operations in the area have used; for example, Dan River Mills’ textile plant in Danville used 8.2 million gallons of water per day.", 
        "shortanswer" => "true", 
        "image" => "Q7---water-graphic.jpg",
        "caption" => ""
    ), array(
        "question" => "Yellowcake, the commodity a mining company like Virginia Uranium would produce, is dangerous in the hands of terrorists.", 
        "answer" => "Yellowcake is harmless in the hands of terrorists.  This natural uranium produced at uranium mines and mills must go through the three major processing steps of conversion, enrichment, and fuel rod fabrication before it can even be used in the nuclear reactors that power our world.  Commercial-grade uranium fuel for reactors is usually enriched up to 3.5-5% uranium-235.", 
        "shortanswer" => "false", 
        "image" => "Q8---yellowcake.jpg",
        "caption" => "Barrel of yellowcake"
    ), array(
        "question" => "The uranium that mining companies produce is a very hazardous and explosive material.", 
        "answer" => "Yellowcake, the form of natural uranium produced in the mining and milling process, is not flammable and cannot explode.  It is far safer to transport than common fuels like gas and propane.  Like lead, it is only harmful if ingested in significant quantities.", 
        "shortanswer" => "false", 
        "image" => "Q9---gas-truck.jpg",
        "caption" => "Gas is explosive.  Uranium is far safer for transport"
    ), array(
        "question" => "If Virginia’s legislature lifts the moratorium on uranium mining, mines will open up all over the state.", 
        "answer" => "Uranium, a common element, exists in virtually any rock and in seawater in very small concentrations, but companies do not extract uranium from seawater. The process required to do so is far more expensive than the price of uranium, which means that it is not currently possible to profit from such means of uranium production. Likewise, uranium occurs in Virginia outside of Coles Hill, but, as the National Academy of Sciences has written, it is not worth mining at prevailing prices.", 
        "shortanswer" => "false", 
        "image" => "Q10---state-capitol.jpg",
        "caption" => ""
    ), array(
        "question" => "Strict federal regulations govern the disposals of tailings, the byproduct of uranium mining. Under federal regulations, tailings management facilities must be designed to last for 1,000 years and withstand severe weather events, including hurricanes and floods.", 
        "answer" => "The Nuclear Regulatory Commission, the federal agency regulating uranium mills and tailings disposal, has designated below-grade disposal as the prime option for tailings disposal.  Tailings disposal cells must have impermeable liners.  They cannot be located in areas at all prone to flooding. In fact, current industry best practices recommend that tailings be returned to the same geologic structure which held the uranium ore for millions of years prior to mining.", 
        "shortanswer" => "true", 
        "image" => "Q11---Puy-de-L'Ages,-Now-a-Trout-Fishing-Lake,-June-2009.jpg",
        "caption" => "Former open pit mine at Puy de L’Ages, France, now a trout fishing pond"
    ), array(
        "question" => "Pittsylvania County and Virginia taxpayers will be expected to pay for mine reclamation and monitoring when the mine closes.", 
        "answer" => "The Nuclear Regulatory Commission requires uranium mill operators to post surety bonds to cover reclamation and long-term monitoring costs. Operations cannot begin before these bonds are posted, and the amount of the bonds is determined by the NRC during the permitting process and reviewed annually.   For example, Pinion Ridge Mill in Colorado is required to post $11 million in bonds and Homestake Grants in New Mexico $33 million.", 
        "shortanswer" => "false", 
        "image" => "Q12---elliotlakepic.jpg",
        "caption" => "Elliot Lake, Canada, the former “Uranium Capital of the World.”"
    ), array(
        "question" => "<p>So, would you have passed Uranium 101?  If not, don’t fear.  You may find plenty of general information about uranium and the mining industry in our <a href='http://www.virginiauranium.com/reference-library/'>Reference Library</a>, and you’ll be able to learn more about Virginia Uranium and our plans <a href='http://www.virginiauranium.com/who-we-are/'>here</a>.</p>
        <p><a href='http://www.virginiauranium.com/contact/'>Click here</a> to tell us a little about yourself and send us any questions you may have about Virginia Uranium and our plans.</p>"
    )
);

function isNumeric($num="") {
    if(is_numeric($num) && $num = round($num) && $num >= 0)
        return true;
    return false;
}

/* sets default question and score, then checks the session to see if one is already set */
$currQuestion = 1;
$numCorrect = 0;
if(isset($_SESSION['uQuiz_Question']) && isNumeric($_SESSION['uQuiz_Question']) && $_SESSION['uQuiz_Question'] > 0 && $_SESSION['uQuiz_Question'] <= sizeof($questions))
    $currQuestion = intval($_SESSION['uQuiz_Question']);
if(isset($_SESSION['uQuiz_Score']) && isNumeric($_SESSION['uQuiz_Score']) && $_SESSION['uQuiz_Score'] >= 0 && $_SESSION['uQuiz_Score'] < sizeof($questions))
    $numCorrect = intval($_SESSION['uQuiz_Score']);

/* if user has answered, test answer and alter score, go to next question */
if(isset($_GET['val']) && isNumeric($_GET['val'])) {
    $testVal = "";

    if(intval(($currQuestion."tru"), 36) == $_GET['val']) 
        $testVal = "true";
    else if(intval(($currQuestion."fal"), 36) == $_GET['val'])
        $testVal = "false";

    if($testVal != "") {
        if($questions[$currQuestion]['shortanswer'] == $testVal)
            $numCorrect++;
        $currQuestion++;
    }
}

/* 
if on last page of quiz, delete the session so the next visit will start the quiz again
otherwise just store the updated info in the session 
*/
if($currQuestion == sizeof($questions)) {
    unset($_SESSION['uQuiz_Question']);
    unset($_SESSION['uQuiz_Score']);
} else {
    $_SESSION['uQuiz_Question'] = $currQuestion;
    $_SESSION['uQuiz_Score'] = $numCorrect;
}
?>

sitenew.js

jQuery(document).ready(function() {
    jQuery(".quiz_button_true,.quiz_button_false")
        .click(function() {
            var $sibling = jQuery(this).siblings();
            var $answer = jQuery(this).parent().siblings(".answer");
            var correct = false;

            if(!jQuery(this).hasClass("active") && !$sibling.hasClass("active")) {
                jQuery(this).addClass("active");

                $sibling
                    .addClass("inactive")
                    .animate({ "opacity": .4 }, 300)
                .end();

                if(($answer.find(".hide").html() == "true" && jQuery(this).hasClass("quiz_button_true")) || ($answer.find(".hide").html() == "false" && jQuery(this).hasClass("quiz_button_false")))
                    correct = true;

                $answer.each(function() {
                    if(!correct)
                        jQuery(this).find("strong").css("color", "#af0000");

                    jQuery(this)
                        .css({ "opacity": 0, "display": "block" })
                        .animate({ "opacity": 1 }, 300)
                    .end();
                });

                var currQ = jQuery("#body").find("input[name='currentQuestion']").val();

                jQuery(".quiz_next")
                    .attr("href", ("?val=" + intval(currQ + ((jQuery(this).hasClass("quiz_button_true")) ? "tru" : "fal"), 36)))
                    .addClass("active")
                .end();
            }
        })
    .end();

    jQuery(".quiz_next")
        .click(function(e) {
            if(jQuery(this).hasClass("active"))
                window.location.href = jQuery(this).attr("href");

            return false;
            e.preventDefault();
        })
    .end();
});

function intval(mixed_var, base) {
    var tmp;
    var type = typeof(mixed_var);

    if(type === 'boolean')
        return +mixed_var;
    else if(type === 'string') {
        tmp = parseInt(mixed_var, base || 10);
        return (isNaN(tmp) || !isFinite(tmp)) ? 0 : tmp;
    } else if(type === 'number' && isFinite(mixed_var))
        return mixed_var | 0;

    return 0;
}

I am really hoping that someone here will be able to help me get over this hump. I would hate to have to code a whole new quiz.

Related posts

Leave a Reply

1 comment