making a simple quiz system with direct answer - javascript

I know there are a lot of free/paid quiz systems out there, but none are customizable enough, especially that I need it in RTL direction.
Anyway, I have made this simple script: fiddle
<!-- question 1 -->
<div id="01">hello there
<br />
<input id="01_correct_btn" type="button" onclick="getElementById('01_correct').style.display = 'block';
getElementById('01_continue').style.display = 'block'; this.style.display = 'none'; getElementById('01_wrong_a').style.display='none';getElementById('01_wrong_b').style.display='none'" />Hi
<br />
<input id="01_wrong_a" type="button" onclick="getElementById('01_wrong').style.display = 'block';
getElementById('01_continue').style.display = 'block'; this.style.display = 'none'; getElementById('01_correct_btn').style.display='none';
getElementById('01_wrong_b').style.display='none'" />bye
<br />
<input id="01_wrong_b" type="button" onclick="getElementById('01_wrong').style.display = 'block';
getElementById('01_continue').style.display = 'block'; this.style.display = 'none'; getElementById('01_correct_btn').style.display='none';
getElementById('01_wrong_a').style.display='none'" />thanks
<br />____________________
<div id="01_correct" style="display:none">yep, you're right...
<br />
</div>
<div id="01_wrong" style="display:none">You are so wrong
<br />
</div>
<input style="display:none" type="button" id="01_continue" onclick="getElementById('01').style.display = 'none';
getElementById('02').style.display = 'block'" value="continue" />
</div>
<!-- question 2 -->
<div id="02" style="display:none">question 2: Welcome to the real world</div>
1: How can I hide all wrong answers without having to add all their ids (getElementByClassName didn't work)
2: Instead of re-copying the script for each question, can this be done by JavaScript where in each new form:
a. a "correct_btn" displays a "correct_note" and hides all other buttons
b. "wrong_btn"s display a "wrong_note" and hides all other buttons
c. both "correct_btn" and "wrong_btn"s will display the continue button
d. "continue" button hides current div/form and displays next one
It would be much easier this way to create as much questions as possible.
Thank you very much.

I would suggest looking at the HTML class system. As you can assign one class to multiple items. Then just create a script instead of calling the onclick javascript event.
I know you requested javascript, but you tagged JQuery and as I feel a JQuery script would serve you better for what you are trying to do I suggested that. Doing this with Javascript could get very wordy and complicated.
HTML
<div id="Q1">Hello There<br/>
<div class = "Q1 correct choice"><input type="button"/>Hi</div>
<div class = "Q1 wrong choice"><input type="button"/>Bye</div>
<div class = "Q1 wrong choice"><input type="button"/>Thanks</div>
</div>
<div id="Q1_Correct" style="display: none;">You are correct</div>
<div id="Q1_Wrong" style="display: none;">You are wrong</div>
You can also set up a generic correct/wrong message to be displayed.
Now, using JQuery would probably be easiest... like in this fiddle : http://jsfiddle.net/p5YY4/1/ (its not perfect, but some styling should solve some click issues... but I think you can get the gist)
JQuery
$('.choice').on('click', function() {
var parent = $(this).parent().attr('id');
if($(this).hasClass('correct')){
$('.choice').hide();
var response = "#" + parent + "_Correct";
$(response).show();
}
if($(this).hasClass('wrong')){
$('.choice').hide();
var response = "#" + parent + "_Wrong";
$(response).show();
}
});
Let me know if you have any questions about this.
For making the script native to one document here is what you would need to set up to get it to work :
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//The script I have already provided should go here
});
</script>
You can also create a separate document and call it lets say quizWorker.js
and then using the same layout as I just stated (in the js file I would also put the script in the $(document).ready function)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.js"></script>
<script type="text/javascript" src="quizWorker.js"></script>

Related

How to share a post with image using addThis plugin in jquery

How can i share a post in facebook with the image using addThis. I have written this code to share in facebook,twitter and mail.
Now i can able to post or share the content without having the image and am getting like this(Refer Image)What i get.
Please help me to post with the image and caption.
I have added my code in fiddle or even you can see it in this https://jsfiddle.net/x34nnwcs/
(function () {
addthis.init();
function navigatePage(e) {
var pageId = $(this).attr("id"),
$pageContent, sharingMarkup, content,
config = $.extend(true, {}, window.addthis_config),
share = $.extend(true, {}, window.addthis_share);
if (pageId != "pageContent") {
config["some_property"] = "some value";
share.title = $(this).html();
share.url = "http://" + pageId + ".not-a-tld";
share.photo = "http://res-5.cloudinary.com/demo/image/upload/dpr_1.0,f_auto,w_365,h_133,c_fill,g_south,o_60/group.jpg";
$pageContent = $("#pageContent");
sharingMarkup = $("#sharing_markup").html();
content = $(".pageC").html();
console.log(content);
$pageContent.html(content + sharingMarkup);
addthis.toolbox(".page_sharing_toolbox", config, share);
addthis.toolbox(".page_sharing_facebook", config, share);
}
$("#page1").click(navigatePage);
}
navigatePage.call(document.getElementById("pageContent"));
}());
<div id="pageContent">
<button id="page1">Page 1</button>
<div class='pageC'>
<img src='http://res-5.cloudinary.com/demo/image/upload/dpr_1.0,f_auto,w_365,h_133,c_fill,g_south,o_60/group.jpg'/>
<p>this is a simple paragraph that is meant to be nice and easy to type which is why there will be mommas no periods or any capital letters so i guess this means that it cannot really be considered a paragraph but just a series of run on sentences this should help you get faster at typing as im trying not to use too many difficult words in it although i think that i might start making it hard by including some more difficult letters I'm typing pretty quickly so forgive me for any mistakes i think that i will not just tell you a story about the time i went to the zoo and found a monkey and a fox playing together they were so cute and i think that they were not supposed to be in the same cage but they somehow were and i loved watching them horse</p>
<p>
</div>
</div>
<script id="sharing_markup" type="text/html">
<div class="page_sharing_facebook addthis_toolbox facebook_like">
<a class="addthis_button_facebook_like" title="Facebook Like"></a>
</div>
<div class="page_sharing_toolbox addthis_toolbox addthis_default_style" style="width:290px;">
<div class="share-icons" id="share-icons">
<a class="addthis_button_email left" title="Email"></a>
<a class="addthis_button_facebook left" title="Facebook"></a>
<a class="addthis_button_twitter left last" title="Twitter"></a>
<a class="addthis_button_google left" title="Google"></a>
</div>
</div>
</script>
<script id="page1content" type="text/html">
</script>
<!-- the async parameter has been added, query parameter style, to the hash so that things won't render until you explicitly call addthis.init() -->
<script src="//s7.addthis.com/js/300/addthis_widget.js#async=1&pubid=atblog"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
you need only to add this meta tag to your <Head> on HTML code
<meta content="your image source" property="og:image">

JavaScript /Jquery : A for loop function with some special usage

This application have 2 components, a HTML page which contain some element and a JavaScript to generate buttons.
I will try to give out a simplify example in the question for now, but if there's something unclear then i would upload the full code later.
I am using HandleBar.js to generate different contents in the html but don't worry if you don't have any idea about this plugin i will make another non-handlebar.js version.
Consider the Html part looks like below:
HandleBar.js version
//example:
//{{feedId}} = 0t454g465754754h456
//{{url}} = www.jegdo.co.uk
{{each}}
<div class="feedIdChecker">{{feedId}}</div>
<div class="{{feedId}}-EditRegionUrl" >{{url}}</div>
<button class="output-{{feedId}}">Output</button>
{{/each}}
Then i have a JQuery function which would output the url
var feedId = $(".feedIdChecker").html();
$('".output-'+feedId+'"').click(function(){
var postUrl = $('".'+feedId+'-EditRegionUrl"').html();
console.log(postUrl );
});
});
}
I found there's no way to identify which button is which. Since i need to declare the var feedID outside the button, it would always get the first feedID it founds and append to all buttons, how may i solve it? Please tell me if this question is confuse, i will try to explain it in a better way.
There's lots of people trying to help me but it seem i need to give out some more details in order for better understanding:
Javascript:
var initRegionEdit = function(){
var feedId = $(".feedIdChecker").html();
$(".CTHK").click(function(){
var postUrl = ($(this).prev('div').html());
})
}
HTML
<div class="EditRegionUrl" >{{url}}</div>
<div class="feedIdChecker">{{feedId}}</div>
{{#if region}}
<span class="dropdown"><i class="fa fa-map-marker" aria-hidden="true" style="color:gray;"></i>
<span class="result-date result-date-region" type="button" data-toggle="dropdown">{{region}}
<span class="caret"></span></span>
<ul class="dropdown-menu" style="min-width:100px;text-align:center;">
<li class="CTHK" data-url="{{url}}" style=" margin-top: 0px !important;margin-bottom: 0px !important;">Hong Kong</li><div class="divider"></div>
<li class="CTTW" style=" margin-top: 0px !important;margin-bottom: 0px !important;">Taiwan</li><div class="divider"></div>
</ul>
</span>
{{/if}}
I wish above information can help
So when you select $(".feedIdChecker") you actually get an array of all matching elements, but as soon as you call .html it only gets you the first. So to solve your issue we need to loop over all the $(".feedIdChecker")s like so:
$(".feedIdChecker").each(function(i, e) {
var feedID = $(e).html();
$('.output-'+feedID).click(function(){
var postUrl = $("." + feedID + "-EditRegionUrl").html();
console.log(postUrl);
});
});
This will attach the click handler to each of the buttons.
You could use the handlebars.js each/index feature to do this:
<button id="whatever-{{#index}}"
class="output-{{feedId}}">
Output
</button>
I'm assuming you need an answer on how to apply a unique id to each button, not how to bind click handlers to them (which other people have answered anyway)
May this version be quicker and with less code.
$('[class*=output-]').click(function() {
var feedId = this.className.split("-")[1];
var postUrl = $('.EditRegionUrl-' + feedId).html();
alert(postUrl);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="feedIdChecker">1</div>
<div class="EditRegionUrl-1" >URL1</div>
<button class="output-1">Output1</button>
<div class="feedIdChecker">2</div>
<div class="EditRegionUrl-2" >URL2</div>
<button class="output-2">Output2</button>
Can you just put url in the button and a generic class:
<button class="output-{{feedId}} btn-class" data-url="{{url}}">Output</button>
and then
$('.btn-class').click(function(){
console.log($(this).data('url') );
});
Or even just without changing your markup at all
$("button").click(function(){
console.log($(this).prev('div').text());
});

jQuery ToDo list

I work on the simple ToDo list written on jQuery (and JS, of course).
I already created the static ToDo list with a possibility to add new items only by editing the code. It is logically that I am going to create a dynamic list now.
I've already tried some methods, like .load() code from external file, create .after(), but it all goes wrong for me.
What would you suggest me to do?
You may find all the source codes in strasbourgmeetings.org/ccc
I would be very grateful if you could help me solving this question.
Gloserio, yes, Add Item does not work now, because I of the problem I described.
ncubica, the problem is that at the moment I am not able to add new items to my list (only bu editing the code). Dynamic means that it would be possible to add/delete items. To do that I tried to use .after() method with the function inside it, that will copy the <li id="item1">List item here</li><li id="buttons1">Buttons here</li> (roughly speaking), but it puts all list items on the upper side and all buttons to the bottom.
This is a part of the JS code:
<script>
// Waiting for the document to load
$(document).ready(function() {
// Wanted to create a dynamic item list, that's why I used this variable. I thought it would
// generate unique IDs (there was 'id++' somewhere in the function I already deleted).
var id = 1;
// This is going to be used as an action for 'Add Item' button. (It is not a button, actually, it is just <span> with cursor: pointer. Using <a> causes page reload);
$('.add').click(function() {
$('#item'+id).after(function(i) { // '#item'+id should be something like this in the code: #item2, #item3, etc.
})
})
// 'Done' button
$('#done1').click(function() {
console.log('# "Done" button pressed');
$('#list1').css('background-color','#89f49a').css('border','1px solid #16bf31').css('text-decoration','line-through').css('color','#817f7f').css('font-weight','normal');
console.log('# Item doned successfully');
});
// 'Undone' button (is gonna be renamed to 'Reset');
$('#undone1').click(function() {
console.log('# "Undone" button pressed');
$('#list1').css('background-color','').css('border','').css('text-decoration','').css('color','').css('font-weight','normal');
});
// 'Working' button
$('#working1').click(function() {
$('#list1').css('background-color','#edc951').css('border','1px solid #dda119').css('font-weight','bold').css('color','#000').css('text-decoration','none');
});
// 'Cancel' button
$('#cancel1').click(function() {
$('#list1').css('background-color','#ff8c8c').css('border','1px solid #ea2c2c').css('font-weight','normal').css('text-decoration','line-through').css('color','#f00');
});
// 'Delete' button
$('#del1').click(function() {
$('div#dlist1').remove();
$('li#action1').remove();
});
});
</script>
And HTML part:
<div class="list">
<ul id="sortable">
<div class="list-item" id="item1"><div class="spacer1" id="spacer1"></div>
<div class="l-element" id="dlist1"><li id="list1" class="ui-widget ui-state-default">Create add feature</div>
<li id="action1" class="action"><input type="button" value="Done" class="done" id="done1"><input type="button" value="Undone" class="undone" id="undone1"><input type="button" value="Working" class="working" id="working1"><input type="button" value="Cancel" class="cancel" id="cancel1"><span id="del1" class="delete">Delete</span></li>
<div class="spacer"></div></div>
</ul>
<div>
As you can see, there is only 1 list item I wrote. IDs are static and can not be changed at the moment. All I need is to change IDs (ok, it will be var id = 1; id++) and to add the part of the code (inside <div class="list-item")
why don't you try jQuery's .clone() and attach it to the "Add Item" behaviour?
You can check it here.
I personally made one as well, and it works really simply, a checkbox, the text, followed by a delete button.
Works great, though I'm still working on a way to make it save it after you close the browser.
jQuery code:
function addListItem() {
var textToAdd = $('#new-text').val(); // The finish class is just for css styling
$('#list').append('<li class="item"><input type="checkbox" class="finish" />' + textToAdd + '<button class="delete">Delete</button></li>');
$('#new-text').val('');
}
function deleteItem() {
$(this).parent().remove();
}
$(document).ready(function() {
$('#add').on('click', addListItem);
$(document).on('click', '.delete', deleteItem);
});
HTML code:
<!DOCTYPE html>
<html>
<head>
<title>To Do List</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h2>To Do List</h2>
<p>Project started on <strong>4-1-2015</strong>.</p>
<input type="text" id="new-text" /><button id="add">Add</button>
<ul id="list">
</ul>
<script src="jquery.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
Hope this helped :)

Mootools Click Event Problem

This peace of code works for the first click. but then it seems to not be able to get new ID from next click. the idea behind it is to show one piece of a form and with click on a button it hides first and shows second part. any idea what im doing wrong?
i guess it has something to do with "this" but from my understanding it should get the id from the second link also.
window.addEvent('domready', function()
{
$('page_2').slide('hide');
$('page_3').slide('hide');
$('page_4').slide('hide');
$('page_5').slide('hide');
var togglePrefix = 'toggle_', boxPrefix = 'page_', emptyPrefix = '';
var links = $('submit_box').getElements('a');
links.addEvent('click', function(e)
{
e.stop();
var id = $(this.get('id').replace(togglePrefix,emptyPrefix));
var id_new = parseInt($(this).get('id').replace(togglePrefix, emptyPrefix)) + 1;
var next = ('page_'+id_new);
var id_old = $(this.get('id').replace(togglePrefix,boxPrefix));
$(id_old).set('slide', {duration: 'long', transition: 'linear'});
$(id_old).slide('out');
$(next).slide('in');
});
});
the html follows this pattern:
<div id="page_1">
<div id="inhalt-gewinn">
<div id="gewinn_bild"></div>
<div id="gewinn_form">
<form id="gewinnspiel" name="gewinnspiel" method="post" action="<?=$_SERVER[PHP_SELF]; ?>">
<div id="input_box">
<div><input type="radio" name="frage1" value="Kamille" /><span>Kamille</span></div>
<div><input type="radio" name="frage1" value="Kaktus" /><span>Kaktus</span></div>
<div><input type="radio" name="frage1" value="Krokus" /><span>Krokus</span></div>
</div>
<div id="submit_box"><a id="toggle_1" class="frage">nächste Frage...</a></div>
</div>
<div id="gewinn_werbung"></div>
</div>
</div>
If I understand the example, you've got a bunch of divs with id page_1, page_2 and so on. In every div is a div with the id "submit_box". When you wrote $('submit_box').getElements('a') it will add the event only to the first div cause an id has to be unique. You cant have more then one element with a unique id in the page. So to get your example work change the id to a classname and use $$('div.submit_box a').
The use of ID´s multiple times on the page ruined the code!
After fixing this it worked fine

jQuery counting elements by class - what is the best way to implement this?

What I'm trying to do is to count all of the elements in the current page with the same class and then I'm going to use it to be added onto a name for an input form. Basically I'm allowing users to click on a <span> and then by doing so add another one for more of the same type of items. But I can't think of a way to count all of these simply with jQuery/JavaScript.
I was going to then name the item as something like name="whatever(total+1)", if anyone has a simple way to do this I'd be extremely grateful as JavaScript isn't exactly my native tongue.
Should just be something like:
// Gets the number of elements with class yourClass
var numItems = $('.yourclass').length
As a side-note, it is often beneficial to check the length property before chaining a lot of functions calls on a jQuery object, to ensure that we actually have some work to perform. See below:
var $items = $('.myclass');
// Ensure we have at least one element in $items before setting up animations
// and other resource intensive tasks.
if($items.length)
{
$items.animate(/* */)
// It might also be appropriate to check that we have 2 or more
// elements returned by the filter-call before animating this subset of
// items.
.filter(':odd')
.animate(/* */)
.end()
.promise()
.then(function () {
$items.addClass('all-done');
});
}
Getting a count of the number of elements that refer to the same class is as simple as this
<html>
<head>
<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alert( $(".red").length );
});
</script>
</head>
<body>
<p class="red">Test</p>
<p class="red">Test</p>
<p class="red anotherclass">Test</p>
<p class="red">Test</p>
<p class="red">Test</p>
<p class="red anotherclass">Test</p>
</body>
</html>
var count = $('.' + myclassname).length;
for counting:
$('.yourClass').length;
should work fine.
storing in a variable is as easy as:
var count = $('.yourClass').length;
HTML:
<div>
<img src='' class='class' />
<img src='' class='class' />
<img src='' class='class' />
</div>
JavaScript:
var numItems = $('.class').length;
alert(numItems);
Fiddle demo for inside only div
try
document.getElementsByClassName('myclass').length
let num = document.getElementsByClassName('myclass').length;
console.log('Total "myclass" elements: '+num);
.myclass { color: red }
<span class="myclass" >1</span>
<span>2</span>
<span class="myclass">3</span>
<span class="myclass">4</span>

Categories