Transferring values using js switch - javascript

Using jStorage.js, I've transferred some values, referring to English programs like "starting", "primary", "uni" and so on, from one page to another in a Joomla site using this script. This works OK. Each of the values is displayed in the title on its relevant second page.
Here is the js:
jQuery(document).ready(function(){
"use strict";
jQuery("p.enrol_para").on("click", function(evnt){
var elementId = evnt.target.id;
jQuery.jStorage.set("program", elementId);
});
jQuery("div#register_title").prepend(document.createTextNode(jQuery.jStorage.get("program")+" "));
});
and the html fragment:
<p class="enrol_para"><span class="enrol_text">Enrol/ลงทะเบียน</span></p>
However, what I want is for "starting" to show "Starting English", "primary" to show "Primary School" and so on. I tried to do this using a js switch statment in this way:
jQuery(document).ready(function(){
"use strict";
jQuery("p.enrol_para").on("click", function(evnt){
var elementId = evnt.target.id;
jQuery.jStorage.set("program", elementId);
});
var progName = JQuery.jStorage.get("program");
switch (progName){
case "starting":
jQuery("div#register_title").prepend(document.createTextNode("Starting English"+" "));
break;
case "primary":
jQuery("div#register_title").prepend(document.createTextNode("Primary School English"+" "));
break;
case "high":
jQuery("div#register_title").prepend(document.createTextNode("High School English"+" "));
break;
case "senior":
jQuery("div#register_title").prepend(document.createTextNode("Senior School English"+" "));
break;
case "uni":
jQuery("div#register_title").prepend(document.createTextNode("University English"+" "));
break;
case "profession":
jQuery("div#register_title").prepend(document.createTextNode("Professional and Career English"+" "));
break;
default:
jQuery("div#register_title").prepend(document.createTextNode("General English"+" "));
}
});
But this doesn't work. Nothing is displayed in the various page titles. JSHint has OKed the syntax. I thought that using a switch statement would be the best way to go here, but perhaps not. Any help would be much appreciated.

Here is the script that did the trick:
jQuery(document).ready(function(){
"use strict";
jQuery("a.enrol_btn").on("click", function(){
jQuery.jStorage.set("program", jQuery(this).attr("data-program"));
});
jQuery("div#register_title").prepend(document.createTextNode(jQuery.jStorage.get("program")));
});

Related

How can I add a active class to a svg path?

I want to add a active class so that whenever I click on a path it will be active until I click the other one. The minimal way of doing this would be appreciable. I already made this svg clickable using jquery. . Here is my jquery code-
$(document).ready(function () {
$('#mySVG').load("bd-map.html", function () {
$("#bd-map").click(function (evt) {
switch (evt.target.id) {
case "panchagarh":
$('#info').load('info.html #panchagarh') //loading data from info.html
break;
case "bandarban":
$('#info').load('info.html #bandarban') //loading data from info.html
break;
case "comilla":
$('#info').load('info.html #comilla')
break;
case "sylhet":
$('#info').load('info.html #sylhet')
break;
}
});
});
})
This should do it, assuming the element you want the class added to is an SVG that lives inside the #bd-map container. The trick is that you're either clicking on the path or text element, so you have to sniff for tagName and then react accordingly. The path to the path from the text element is $(evt.target).parent().prev('path') (keeping things in jQuery)
$("#bd-map").click(function(evt) {
$("#bd-map").find('path').removeClass('active');
let targ = evt.target.tagName === 'path' ? $(evt.target) : $(evt.target).parent().prev('path');
console.log(targ.attr('id'))
targ.addClass('active')
switch (targ.attr('id')) {
case "panchagarh":
$('#info').load('info.html #panchagarh') //loading data from info.html
break;
case "bandarban":
$('#info').load('info.html #bandarban') //loading data from info.html
break;
case "comilla":
$('#info').load('info.html #comilla')
break;
case "sylhet":
$('#info').load('info.html #sylhet')
break;
}
});

Making Javascript Code Deploy Ready

I need to make this code deploy ready. I can't hard code these URL's in but for some reason any other way of coding this, breaks. Reference this question here: Upon Redirect of Form Submission within iFrame jQuery Not Detecting Updated Src Attribute
I basically need to have the switch check if the location CONTAINS the page name after 'settings/' i.e. iframe-home.php, update.php, or changepassword.php. I think thats how i fix this issue? But i'm not sure how. (Hope that makes sense)
Here is the code:
$(document).ready(function() {
$('iframe#settings-iframe').on('load', function() {
var location = this.contentWindow.location.href;
console.log('location : ', location);
switch (location) {
case "http://localhost/Makoto/profile/settings/iframe-home.php":
console.log(location);
activateHome();
break;
case "http://localhost/Makoto/profile/settings/changepassword.php":
console.log(location);
activatePassword();
break;
case "http://localhost/Makoto/profile/settings/update.php":
console.log(location);
activateName();
break;
}
});
});
Note I assume that you want dynamically check path without host part.
Create new link element, set href to location, compare it to pathname
// replace with this.contentWindow.location.href
var url = "http://localhost/Makoto/profile/settings/iframe-home.php";
/**
* http://localhost/Makoto/profile/settings/iframe-home.php
* will return /Makoto/profile/settings/iframe-home.php
*/
var link = $('<a>', {
href: url
})[0].pathname;
var parts = link.split('/');
var file = parts[parts.length - 1];
console.log(file);
switch (file) {
case "iframe-home.php":
activateHome();
break;
case "changepassword.php":
activatePassword();
break;
case "update.php":
activateName();
break;
}
function activateHome() {console.log('Activating home');}
function activatePassword() {console.log('Activating password');}
function activateName() {console.log('Activating name');}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Javascript: setTimeout and multiple Prompts

I have a javascript code that loads a prompt on page launch: "Do you believe..."
Gets an answer. Returns "I see" Alert no matter what the user inputs, waits for 10,000 milliseconds and then enters a second prompt. Not sure what I'm doing wrong. When I delete the timeout function and everything underneath that, the prompt works just fine but not sure how I can make the rest work.
<!DOCTYPE html>
<html>
<head>
<title>T-Master, what drink would you like?</title>
</head>
<body>
<script>
window.onload=first();
function first(){
var answer = prompt("Do you believe you have the power to change the world?");
switch(answer){
default:
alert("...I see");
setTimeout(function(){
//do what you need here
},
10000);
}
var answer2 = prompt("Master, your drink?");
var text;
switch(answer2){
case "Gatorade":
text = "THat's what I thought sire";
break;
case "Orange Juice":
text = "That's a good choice sir";
break;
case "Bliss"
text = "Hmm, a finer choice than what I expected";
break;
case "nothing";
text = "Very well sir";
break;
default:
text = "I'll get on it";
break;
}
alert(text);
}
</script>
</body>
</html>
You have a mix of async and sync programming there. Your prompt call is sync but the setTimeout is async and will execute after the code that comes after it.
window.onload=first();
function first() {
var answer = prompt("Do you believe you have the power to change the world?");
switch(answer) {
default :
alert("...I see");
setTimeout(function() {
//do what you need here
var answer2 = prompt("Master, your drink?"),
text;
switch(answer2) {
case "Gatorade" :
text = "That's what I thought sire";
break;
case "Orange Juice" :
text = "That's a good choice sir";
break;
case "Bliss" :
text = "Hmm, a finer choice than what I expected";
break;
case "nothing" :
text = "Very well sir";
break;
default :
text = "I'll get on it";
break;
}
alert(text);
}, 10000);
}
}

Outputting a picture based on a variable's number

I'm building a "game" where a user clicks on an image and a number is randomly generated. With this number an image is assigned and displayed. Essentially a Rock, Paper, Scissors game. I'm just trying to get the random image to display. However I'm confused as how to go about setting the variable and then displaying it.
Originally I tried creating a variable that inside the switch would be something as follows
case 1:
cpuChoice = <img id="rock" src="rock.jpg" name="rock" width="265" height="250" />
break;
And then do a $("#result").html(cpuChoice); (result being a div id) However I had no luck with that. Further research seemed to suggest I have to store images in a cache, which is what my code currently is set up for. Though I don't believe I'm understanding how to utilize it properly.
The images I'm using are stored in a file with the pages.
Below is an example of my current javascript page.
$(document).ready(function(){
var cpuImage = new Image();
rock.src = 'rock.jpg';
paper.src = 'paper.jpg';
scissors.src = 'scissors.jpg';
lizard.src = 'lizard.jpg';
spock.src = 'spock.jpg';
$("#paper").click(function(){
var ranNumberOne = 1 + Math.floor(Math.random() * 5);
// the switch is for assigning the image based on what number is generated
switch(ranNumberOne){
case 1:
document['rock'].src = rock.jpg;
break;
case 2:
document['paper'].src = paper.jpg;
break;
case 3:
document['scissors'].src = scissors.jpg;
break;
case 4:
document['spock'].src = spock.jpg;
break;
case 5:
document['rock'].src rock.jpg;
break;
}
document.['blank'].src =cpuImage.src;
});
blank is just the id of a temporary image I have. the code for it is as follows
<img id="blank" src="blank.jpg" name="blank" width="265" height="250" />
I've done alert's to make sure my onclicks and the random number generator are both working, which they are. It appears that my problem is just getting the image that "the computer picks" to show.
Ok. A few issues are happening here, all of which are solvable. So...
$(document).ready(function(){
// You don't need an image object, since you're only
// determining a string for `src` and applying it to an existing
// image object
var cpuImage = "";
/* Below you're assigning `src` properties to objects that don't exist. */
rock.src = 'rock.jpg';
paper.src = 'paper.jpg';
scissors.src = 'scissors.jpg';
lizard.src = 'lizard.jpg';
spock.src = 'spock.jpg';
/* I see what you're trying to do,
but try going about it a bit differently, example: */
var imageBank = {
'rock' : 'rock.jpg',
'paper' : 'paper.jpg',
'scissors' : 'scissors.jpg',
'lizard' : 'lizard.jpg',
'spock' : 'spock.jpg'
};
$("#paper").click(function(){
var ranNumberOne = 1 + Math.floor(Math.random() * 5);
// the switch is for assigning the image based on what number is generated
switch(ranNumberOne){
// Assign your 'cpuImage' variable to the associated imageBank key
case 1:
cpuImage = imageBank['rock'];
break;
case 2:
cpuImage = imageBank['paper'];
break;
case 3:
cpuImage = imageBank['scissors'];
break;
case 4:
cpuImage = imageBank['lizard'];
break;
case 5:
cpuImage = imageBank['spock'];
break;
}
// Old:
document.['blank'].src =cpuImage.src;
// JQuery syntax (assuming you have an image with id `blank`)
// New:
$("#blank").attr('src',cpuImage);
});
Keep in mind, using things like a dictionary AKA an object as an associative array (which the imageBank variable is) helps to include a bunch more information pertaining to rock, scissors, etc. in one easy-to-maintain place. You can add additional info as well, which will save you time and code in the future.
Hope this helps and best of luck!
In honor of Sheldon Cooper, this FIDDLE might help.
JS
$('.clickme').on('click', function(){
var randimage = Math.floor(Math.random() * 5) + 1;
$('.putmehere').html('');
$('.random1').html(randimage);
$('.holder img#i' + randimage).clone().appendTo('.putmehere');
});
html
<div id="container">
<img id="blank" src="blank.jpg" name="blank" width="265" height="250" />
</div>
js
$(function () {
$("#container")
.attr("data-name", $("img", this).attr("id"))
.on("click", function (e) {
var options = ["rock", "paper", "scissors", "lizard", "spock", "blank"];
var r = (function (n) {
return options[(n + Math.floor(Math.random() * options.length - n))]
})(1);
$("img", this).attr({
"id": r,
"name": r,
"src": r + ".jpg"
}).parent().attr("data-name", r);
});
});
jsfiddle http://jsfiddle.net/guest271314/e3EXs/

jQuery/Javascript scope, maybe variable scope conflict

I am trying to code a menu bar for my site in JS - the problem I'm having is that I am using a variable as a 'which category is unfolded' switch, and it does not seem to register. Firebug seems to tell me it's not defined, and or stays zero.
var navOpen = 0;
$(function() {
///////////bunch of other functions here
//When designWork is clicked
$(".designwork").click(function(){
switch(navOpen)
{
case 0:
$(".navsub:hidden",this).slideDown("slow");
navOpen = 1; break;
case 1:
break;
case 2:
$("div.artProjects .navsub").slideUp("fast");
$(".navsub:hidden",this).slideDown("slow");
navOpen = 1; break;
default:
break;
}
});
//When artProjects is clicked
$(".artprojects").click(function(){
switch(navOpen)
{
case 0:
$(".navsub:hidden",this).slideDown("slow");
navOpen = 2; break;
case 1:
$("div.designWork .navsub").slideUp("fast");
$(".navsub:hidden",this).slideDown("slow");
navOpen = 2; break;
case 2:
break;
default:
break;
}
});
});
For a reason that is probably obvious, but I'm not seeing it, both menus open when clicked in the manner they should, but they do not close the other menu... help me out here, what am I missing?
$("div.designWork .navsub") should be $("div.designwork .navsub")
and
$("div.artProjects .navsub") should be $("div.artProjects .navsub")
capitals ...
Well, I think it has to do with the fact that in both cases you refer to ".navsub:hidden" without specifying precisely which navsub you really mean. You probably want to add either div.designWork or div.artProjects in front of it to specify which menu should slidedown.

Categories