I've searched but frankly, do not know enough about JS to make sense of all of the other "combine these 2 functions" posts already out there.
I am using a script to slide out a Contact Panel. I duplicated this script to then slide out the About Panel.
I want to consolidate both into one script to tidy things up. Possible?
Contact Panel:
<script type="text/javascript">
function showContactPanel() {
var elem = document.getElementById("contact-panel");
if (elem.classList) {
elem.classList.toggle("show");
} else {
var classes = elem.className;
if (classes.indexOf("show") >= 0) {
elem.className = classes.replace("show", "");
} else {
elem.className = classes + " show";
}
console.log(elem.className);
}
}
</script>
Duplicated for the About Panel:
<script type="text/javascript">
function showAboutPanel() {
var elem = document.getElementById("about-panel");
if (elem.classList) {
elem.classList.toggle("show");
} else {
var classes = elem.className;
if (classes.indexOf("show") >= 0) {
elem.className = classes.replace("show", "");
} else {
elem.className = classes + " show";
}
console.log(elem.className);
}
}
</script>
You could pass the panel ID as a parameter:
function showPanel(id) {
var elem = document.getElementById(id);
if (elem.classList) {
elem.classList.toggle("show");
} else {
var classes = elem.className;
if (classes.indexOf("show") >= 0) {
elem.className = classes.replace("show", "");
} else {
elem.className = classes + " show";
}
console.log(elem.className);
}
}
and then call it that way:
showPanel("about-panel");
or
showPanel("contact-panel");
So change your function signature to take a parameter for the element in question:
function showPanel(panelId) {
var elem = document.getElementById(panelId);
...
and call it:
showPanel("contact-panel");
You could pass the id of the panel as an argument to the function:
<script type="text/javascript">
function showPanel(panelId) {
var elem = document.getElementById(panelId);
if (elem.classList) {
elem.classList.toggle("show");
} else {
var classes = elem.className;
if (classes.indexOf("show") >= 0) {
elem.className = classes.replace("show", "");
} else {
elem.className = classes + " show";
}
console.log(elem.className);
}
}
</script>
See JavaScript Function Parameters for more information on function parameters.
Related
I am trying to display multiple child elements in jQuery but only the first child element gets displayed. I can force the browser to show all of them through Inspect and changing the css display from none to block. Can anyone help me find the problem in my code.I use Radio buttons, this is the code :
<script type="text/javascript">
$(document).ready(function () {
$('##radioButtonListSectionId input[type="radio"]
[checked="checked"]').each(function () {
ShowRadioButtonListDependentField(this, false);
});
});
$('##radioButtonListSectionId input[type="radio"]').change(function
() {
var result = $(this).val();
$('##uniqueID-hidden').val(result);
ShowRadioButtonListDependentField(this, false);
});
function ShowRadioButtonListDependentField(element, show) {
debugger;
var fieldKey = $(element).val(), children;
var currentId = element.attributes["currentid"].value;
if (currentId != 0) {
if ($('.main-dialogbox.modal.fade.in').length > 0)
children = $('.modal-body .control-group[parentid=' +
currentId + ']');
else if ($('.idea-task.open').length > 0)
children = $('.idea-task .control-group[parentid=' +
currentId + ']');
else
children = $('.control-group[parentid=' + currentId +
']');
if ($(element).is(":checked") && $(element).is(":visible"))
show = true;
else
show = false;
children.hide();
children.each(function () {
var keys =
this.attributes["parentOptionKey"].value.split("</br>");
var haschildren = this.attributes["haschildren"].value;
for (var i = 0; i < keys.length; i++) {
if (keys[i] == fieldKey) {
if (show) {
$(this).show();
show = false;
$(this.getElementsByClassName("ishidden")).val("False");
} else {
$(this).hide();
$(this.getElementsByClassName("ishidden")).val("True");
if (haschildren.toLowerCase() == "true") {
ShowCheckListDependentField(this,
false);
}
}
}
else {
$(this.getElementsByClassName("ishidden")).val("True");
}
}
});
}
}
</script>
every body.
I try to make function as each function on jquery i make this code
var $ = function (e){
var d = document
if(e){
if ("#" == e.substring(0, 1)) {
return d.querySelectorAll(e);
} else if ("." == e.substring(0, 1)) {
return d.querySelectorAll(e);
} else if ("." != e.substring(0, 1) && "#" != e.substring(0, 1)){
return d.querySelectorAll(e)
}
}
}
i want it if i write $(".example").style.background = "red";
If you want create each function, this code is work
function each(a,b) {
var c = document.querySelectorAll(a);
for(var i = c.length - 1; i >= 0; i--) {
return b.call(i, c[i]);
}
}
//use
each(".class", function(e) {
e.style.background = "red";
});
You need selector engine like sizzle if you want write $(".class").style.background = "red";
I'm new to web programming, and I'm trying to complete a simple guessing game project.
Right now I'm stuck because I'm trying to update an unordered list with the player's past guesses, but the page does not update.
Here is my jQuery code:
$(document).ready(function() {
game = new Game;
var guessNum
onSubmit = function(event){
event.preventDefault();
var input = $('#player-input');
var guess = +input.val();
input.val('');
var result = game.playersGuessSubmission(guess);
if (result == 'You have already guessed that number.') {
$('#title').text(result);
} else if (result === 'You Win!' || result === 'You lose.') {
$('#title').text(result);
$('#subtitle').text('Press the reset button to play again.')
$('#hint').prop('disabled', true)
$('#submit').prop('disabled', true)
} else { //this is the relevant portion
guessNum = (game.pastGuesses.length - 1).toString();
$('#' + guessNum).text(guessNum);
}
};
$('#submit').on('click', function(e){
onSubmit(e);
});
$('#player-input').on('keypress', function(e) {
if(e.which == 13) {
e.preventDefault();
onSubmit(e);
};
});
});
Here is the unordered list's html:
<div id='guesses'>
<!-- unordered list of guesses -->
<ul id='past-guesses' class="list-inline center">
<li id='0' class="guess list-group-item ">-</li>
<li id='1'class="guess list-group-item">-</li>
<li id='2' class="guess list-group-item">-</li>
<li id='3' class="guess list-group-item">-</li>
<li id='4' class="guess list-group-item">-</li>
</ul>
</div>
I have also tried not using the identifiers in the html, and instead selecting the li elements this way:
var idStr = "#past-guesses:eq(" + guessNum + ")"
$(idStr).text(game.playersGuess.toString());
In either case, the page does not update with the new values in the unordered list displayed. What am I doing wrong?
EDIT
In response to the request in comments, here's my entire JS file (now slightly edited because I was experimenting with changing the list id's to not begin with a number):
function generateWinningNumber() {
num = Math.random()
if (num === 0) {
return 1;
} else {
roundNum = Math.floor(num*100);
return roundNum + 1;
}
}
function shuffle(array) {
var m = array.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
function Game(){
this.winningNumber = generateWinningNumber();
this.playersGuess = null;
this.pastGuesses = [];
}
Game.prototype.difference = function() {
return Math.abs(this.playersGuess - this.winningNumber);
}
Game.prototype.isLower = function() {
if (this.playersGuess < this.winningNumber) {
return true;
} else {
return false;
}
}
Game.prototype.checkGuess = function() {
if (this.playersGuess === this.winningNumber) {
return "You Win!";
}
if (this.pastGuesses.indexOf(this.playersGuess) > -1) {
return "You have already guessed that number.";
}
this.pastGuesses.push(this.playersGuess);
if (this.pastGuesses.length >= 5) {
return "You Lose.";
} else if (this.difference() < 10) {
return "You're burning up!";
} else if (this.difference() < 25) {
return "You're lukewarm.";
} else if (this.difference() < 50) {
return "You're a bit chilly.";
} else {
return "You're ice cold!";
}
}
Game.prototype.playersGuessSubmission = function(num) {
if (num < 1 || num > 100 || typeof num != 'number') {
throw "That is an invalid guess."
} else {
this.playersGuess = num;
return this.checkGuess();
}
}
Game.prototype.provideHint = function() {
return shuffle([generateWinningNumber(), generateWinningNumber(), this.winningNumber]);
}
newGame = function() {
game = new Game;
return game;
}
$(document).ready(function() {
var game = new Game;
var guessNum
onSubmit = function(event){
event.preventDefault();
var input = $('#player-input');
var guess = +input.val();
input.val('');
var result = game.playersGuessSubmission(guess);
if (result == 'You have already guessed that number.') {
$('#title').text(result);
} else if (result === 'You Win!' || result === 'You lose.') {
$('#title').text(result);
$('#subtitle').text('Press the reset button to play again.')
$('#hint').prop('disabled', true)
$('#submit').prop('disabled', true)
} else {
guessNum = (game.pastGuesses.length - 1).toString();
$('#l' + guessNum).text(guessNum);
}
};
$('#submit').on('click', function(e){
onSubmit(e);
});
$('#player-input').on('keypress', function(e) {
if(e.which == 13) {
e.preventDefault();
onSubmit(e);
};
});
});
});
You need to escape the CSS selector.
try to replace this line:
$('#' + guessNum).text(guessNum);
with this:
var selector = "#\\" + guessNum.toString().charCodeAt(0).toString(16) + " " + guessNum.toString().substr(1);
$(selector).text(guessNum);
you can read more at:
https://www.w3.org/International/questions/qa-escapes
I have a HTML that loads a table from another page. I've got the CSS to work properly, but I can't edit the table using jQuery when it's pooled by the script, only when I have the table directly on the page. I'm guessing that maybe my changes are running before the load? I don't know..
I want to let you know that I'm not a programmer my self, but more of a curious person. I've searched around and found some things, but the lack of knowledge doesn't let me implement them. Hope you can help me.
The Script I use to read the data from the other page (p1.html)
<script type="text/javascript">
var TimerLoad, TimerChange;
var MaxNum, Rafraichir, Changement, ClassementReduit, ClassementReduitXpremier;
var UrlRefresh, UrlChange;
Rafraichir = 30000;
Changement = 150000;
MaxNum = 1;
ClassementReduit = 0;
ClassementReduitXpremier = 10;
function Load(url, target) {
var xhr;
var fct;
if (UrlChange) url = UrlRefresh;
else UrlRefresh = url;
UrlChange = 0;
if (TimerLoad) clearTimeout(TimerLoad);
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP")
} catch (e2) {
try {
xhr = new XMLHttpRequest
} catch (e3) {
xhr = false
}
}
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200)
if (ClassementReduit == 0) document.getElementById(target).innerHTML = xhr.responseText;
else document.getElementById(target).innerHTML = ExtraireClassementReduit(xhr.responseText)
};
xhr.open("GET", url + "?r=" + Math.random(), true);
xhr.send(null);
fct = function() {
Load(url, target)
};
TimerLoad = setTimeout(fct, Rafraichir)
}
function ExtraireClassementReduit(Texte) {
var i, j, CompteurTD, CompteurTR;
var ColPosition, ColNumero, ColNom, ColEcart1er;
var Lignes;
var NouveauTexte;
CompteurTR = 0;
ColPosition = -1;
ColNumero = -1;
ColNom = -1;
ColEcart1er = -1;
Texte = Texte.substring(Texte.indexOf("<tr"));
Lignes = Texte.split("\r\n");
NouveauTexte = '<table width="100%" cellpadding="0" cellspacing="0">';
for (i = 0; i < Lignes.length; i++)
if (Lignes[i].substring(0, 3) == "<tr") {
NouveauTexte += Lignes[i];
CompteurTD = 0
} else if (Lignes[i].substring(0, 4) == "</tr") {
CompteurTR++;
if (CompteurTR == ClassementReduitXpremier + 1) break
} else if (Lignes[i].substring(0, 3) == "<td") {
if (CompteurTR == 0)
if (Lignes[i].indexOf("\"Id_Position\"") != -1) {
ColPosition = CompteurTD;
NouveauTexte += Lignes[i].replace(/ width=".*"/i, "")
} else if (Lignes[i].indexOf("\"Id_Numero\"") != -1) {
ColNumero = CompteurTD;
NouveauTexte += Lignes[i].replace(/ width=".*"/i, "")
} else if (Lignes[i].indexOf("\"Id_Nom\"") != -1) {
ColNom = CompteurTD;
NouveauTexte += Lignes[i].replace(/ width=".*"/i, "")
} else {
if (Lignes[i].indexOf("\"Id_Ecart1er\"") != -1) {
ColEcart1er = CompteurTD;
NouveauTexte += Lignes[i].replace(/ width=".*"/i, "")
}
} else if (CompteurTD == ColPosition || CompteurTD == ColNumero || CompteurTD == ColNom || CompteurTD == ColEcart1er) NouveauTexte += Lignes[i];
CompteurTD++
}
NouveauTexte += "</table>";
return NouveauTexte
}
function Change() {
var Num, Index;
if (document.forms["Changement"].chkChangement.checked) {
Index = UrlRefresh.indexOf(".");
Num = parseInt(UrlRefresh.substring(1, Index)) + 1;
if (Num > MaxNum) Num = 1;
UrlRefresh = "p" + Num + ".html";
UrlChange = 1;
fct = function() {
Change()
};
TimerChange = setTimeout(fct, Changement)
} else if (TimerChange) clearTimeout(TimerChange)
};
</script>
Loading the table into the body
$(document).ready(Load('p1.html', 'result'));
The code I need to run after (it works with the table directly on page or even on a button, but I can't get to work on page load)
function show_hide_column(col_id, do_show) {
var stl;
if (do_show) stl = 'block'
else stl = 'none';
var tbl = document.getElementsByTagName('table')[0];
var index = document.getElementById(col_id).cellIndex;
var rows = tbl.getElementsByTagName('tr');
for (var row = 0; row < rows.length; row++) {
var cels = rows[row].getElementsByTagName('td')
cels[index].style.display = stl;
}
}
function hide() {
show_hide_column("Id_Position", false);
show_hide_column("Id_Equipe", false);
show_hide_column("Id_Vehicule", false);
}
I fired a console.log() message for every stage of the previous code, to know when exactly the table was added to the page, to then hide the columns. Got it to work.
I'm trying to mimic the Google suggestions list with this:
function el(tid) {
return document.getElementById(tid);
}
function addScript(u) {
var head = document.getElementsByTagName('head')[0],
sc2 = document.createElement('script');
sc2.src = u;
head.appendChild(sc2);
setTimeout(function () {
head.removeChild(sc2);
sc2 = null;
}, 600);
} //end addScript()
function suggest(data) {
var sel = el("test");
sel.innerHTML = '';
for (x = 0; x < data[1].length; x++) {
sel.innerHTML += '<li class="uli" >' + data[1][x][0] + '</li>';
}
}
el("inp").onkeyup = function () {
addScript("http://www.google.nl/complete/search?callback=suggest&q=" + this.value);
};
The problem is that I want to be able to come down in the suggestions list using the arrow keys, and secondary I want to show the 'current' suggestion value inside the input field. So I tried something like this using Jquery:
$("#inp").live("keydown", function (e) {
var curr = $('#test').find('.current');
if (e.keyCode == 40) {
if (curr.length) {
$(curr).attr('class', 'uli');
curr = $(curr).next();
}
if (curr.length) {
curr.attr('class', 'uli current');
} else {
$('#center li:first-child').attr('class', 'uli current');
}
}
if (e.keyCode == 38) {
if (curr.length) {
$(curr).attr('class', 'uli');
curr = $(curr).prev();
}
if (curr.length) {
curr.attr('class', 'uli current');
} else {
$('#center li:last-child').attr('class', 'uli current');
}
}
$("#inp").live("keydown", function (e) {
var search_terms = $('li.current').text();
if (e.keyCode == 40) {
$('#inp').val(search_terms);
}
if (e.keyCode == 38) {
$('#inp').val(search_terms);
}
It doesn't work because (I think..) the 'current' suggestion is immediately being requested by the previous code.
I have put everything over here: JS Bin
Why recreate the wheel?
jQuery UI Autocomplete
Or look at other plugins
The problem with your code is you need to cancel out the arrow keypresses when you call to get the values.
el("inp").onkeyup = function () {
//if not the arrow keys, fetch the list
if( ... ){
addScript("http://www.google.nl/complete/search?callback=suggest&q=" + this.value);
}
}
Also what is with el("inp") when you are using jQuery? I expected to see $("foo").keyup( function(){} );