Keyup in Firefox - javascript

I am trying to detect a keypress using the jQuery keyup function, but it does not seem to work in Firefox. Though it does work in Chrome, Edge, IE and Opera.
$(".textfield").contents().keyup(function(evnt) {
document.getElementById("btn_save").style.opacity = "1";
saved = false;
});
".textfield" is an iframe with designmode = 'on' So I'm trying to detect a keyup within a editable iframe.
Here's my iframe, nothing special:
<iframe class="textfield" name="textfield" frameBorder="0"></iframe>
EDIT: (It's one of my first websites, so don't mind the bad code)
HTML
<head>
<title>Notepad - A minimalistic, free online text editor for your notes</title>
<meta charset="utf-8"/>
<meta name="description" content="Notepad is a free, minimalistic, online text editor for quickly writing down, saving and sharing your notes."/>
<link type="text/css" rel="stylesheet" href="style.css"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="filesaver/filesaver.js"></script>
<link href="https://fonts.googleapis.com/css?family=Khula|Roboto|Open+Sans|Barrio|Cairo|Cantarell|Heebo|Lato|Open+Sans|PT+Sans" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>
<!-- Fonts -->
<script>
WebFont.load({
google: {
families: ['Cantarell', "Open Sans"]
}
});
</script>
</head>
<body onload="enableEdit('dark'); handlePaste(); handleDrop(); retrieveNote(); createCookie();">
<!-- Facebook & Twitter Share -->
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/nl_NL/sdk.js#xfbml=1&version=v2.9";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<div id="social">
<div class="fb-share-button" data-href="https://developers.facebook.com/docs/plugins/" data-layout="button_count" data-size="small" data-mobile-iframe="true"><a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2Fplugins%2F&src=sdkpreparse" style="vertical-align:top;zoom:1;*display:inline">Share</a></div>
<a class="twitter-share-button" href="https://twitter.com/intent/tweet"></a>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
</div>
<!-- Page -->
<div id="page">
<!-- Textfield -->
<iframe class="textfield" name="textfield" frameBorder="0"></iframe>
<!-- Toolbar -->
<div id="toolbar">
<h1 class="button" id="btn_bold" onclick="bold();" onmouseenter="onMouseEnter('btn_bold');" onmouseleave="onMouseLeave('btn_bold');"><b>B</b></h1>
<h1 class="button" id="btn_ita" onclick="italic();" onmouseenter="onMouseEnter('btn_ita');" onmouseleave="onMouseLeave('btn_ita');"><i>I</i></h1>
<h1 class="button" id="btn_und" onclick="underline();" onmouseenter="onMouseEnter('btn_und');" onmouseleave="onMouseLeave('btn_und');"><u>U</u></h1>
<img src="img/theme_dark.png" alt="Change theme" class="button theme" id="btn_theme" onclick="changeTheme();" onmouseenter="onMouseEnter('btn_theme');" onmouseleave="onMouseLeave('btn_theme')"; alt="Change theme." title="Theme"></img>
<img src="img/save.png" type="button" id="btn_save" value="submit" onclick="post();" class="button theme" alt="Save note." onmouseenter="onMouseEnter('btn_save');" onmouseleave="onMouseLeave('btn_save')" title="Save note"/>
<img src="img/cloud.png" type="button" id="btn_down" onclick="download();" class="button theme" alt="Download note" onmouseenter="onMouseEnter('btn_down');" onmouseleave="onMouseLeave('btn_down')" title="Download note"/>
<h1 class="button" id="btn_plus" onmousedown="changeFontSize(3);" onmouseenter="onMouseEnter('btn_plus');" onmouseleave="onMouseLeave('btn_plus');">+</h1>
<h1 class="button" id="btn_minus" onmousedown="changeFontSize(-3);" onmouseenter="onMouseEnter('btn_minus');" onmouseleave="onMouseLeave('btn_minus');">-</h1>
</div>
<div id="result"></div>
</div>
<?php
require("dbconnect.php");
$id = 0;
$idvar = $_GET['id'];
if ($idvar != null) {
$sel = "SELECT text from content WHERE id = $idvar";
} else {
$sel = "SELECT text from content WHERE id = 0";
}
$result = mysqli_query($connection, $sel);
if (mysqli_num_rows($result) == 1) {
while ($r = mysqli_fetch_array($result)) {
$content = str_replace('"', '"', $r["text"]);
}
} else {
header("Location: index.html");
}
$result = mysqli_query($connection, "SELECT id FROM content ORDER BY id DESC LIMIT 1;");
if (mysqli_num_rows($result) > 0) {
$lastid = mysqli_fetch_row($result);
}
?>
<div id="hid" style="display:none;" data-info="<?php echo $content; ?>"></div>
<script type="text/javascript">
function post() {
if (!saved) {
var content = getContent();
$.post("note.php", {posttext:content}, function (data) {});
var lastid = "<?php echo $lastid[0]; ?>";
if (content != "") {
increment++;
lastid = parseInt(lastid) + increment;
alert("Note saved at:\nnotepad.com/index.html?id=" + lastid);
document.getElementById("btn_save").style.opacity = "0.3";
document.getElementById("btn_save").title = "Saved at:\nnotepad.com/index.html?id=" + lastid;
saved = true;
} else {
alert("Empty note");
}
}
}
</script>
<script type="text/javascript" src="script.js"></script>
</body>
JavaScript
var color_text;
var color_button_light;
var color_button_dark;
var color_background;
var color_hover;
var brightness;
var font_size = 32;
var saved = false;
var mouseObj;
function getContent() {
return textfield.document.body.innerHTML;
}
var increment;
function download() {
if (getContent() != "") {
var blob = new Blob([getContent()], {type: "text/plain;charset=utf-8"});
saveAs(blob, "note");
} else {
alert("Empty note");
}
}
function retrieveNote() {
var info = $("#hid").data("info");
textfield.document.body.innerHTML = info;
}
$(".textfield").contents().keyup(function(evnt) {
document.getElementById("btn_save").style.opacity = "1";
saved = false;
});
function enableEdit(theme) {
increment = 0;
// Themes
if (theme === 'dark') {
color_text = "#757575";
color_button_light = "#303030";
color_button_dark = "#646464";
color_hover = "#535353";
brightness = 125;
color_background = "#151515";
} else if (theme === 'hacker') {
color_text = "#00BB00";
color_button_light = "#202020";
color_button_dark = "#00BB00";
color_hover = "#009900";
brightness = 125;
color_background = "#000000";
} else if (theme === 'light') {
color_text = "#999";
color_button_light = "#BBBBBB";
color_button_dark = "#757575";
color_hover = "#646464";
brightness = 90;
color_background = "#EEEEEE";
}
// Background Color
document.body.style.backgroundColor = color_background;
document.getElementById("toolbar").backgroundColor = color_background;
// Textfield
textfield.document.designMode = 'on';
var tag = "<link href='https://fonts.googleapis.com/css?family=Open+Sans|Heebo|Lato' rel='stylesheet'><style>body{font-family:consolas, heebo;}</style>"
$(".textfield").contents().find("head").append(tag);
textfield.document.body.style.fontSize = font_size + "px";
textfield.document.body.style.color = color_text;
textfield.document.body.style.padding = "20px";
textfield.document.body.style.tabSize = "4";
textfield.document.body.style.whiteSpace = "pre-wrap";
textfield.document.body.style.wordWrap = "break-word";
textfield.document.body.style.lineHeight = "1.4";
textfield.focus();
// Buttons
document.getElementById("btn_bold").style.color = color_button_light;
document.getElementById("btn_ita").style.color = color_button_light;
document.getElementById("btn_und").style.color = color_button_light;
document.getElementById("btn_plus").style.color = color_button_dark;
document.getElementById("btn_minus").style.color = color_button_dark;
}
function handlePaste() {
textfield.document.addEventListener("paste", function(evnt) {
evnt.preventDefault();
var text = evnt.clipboardData.getData("text/plain");
document.getElementById("btn_save").style.opacity = "1";
saved = false;
textfield.document.execCommand("insertText", false, text);
});
}
function handleDrop() {
textfield.document.addEventListener("drop", function (evnt) {
evnt.preventDefault();
document.getElementById("btn_save").style.opacity = "1";
saved = false;
var text = evnt.dataTransfer.getData("text/plain");
textfield.document.execCommand("insertText", false, text);
});
}
var sources = ["theme_dark.png", "theme_light2.png", "theme_hacker.png"];
var sources2 = ["save_dark.png", "save.png", "save_hacker.png"];
var themes = ["dark", "light", "hacker"];
var iterator;
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function createCookie() {
if (getCookie("theme") == "") {
iterator = 0;
} else {
iterator = getCookie("theme");
}
document.getElementById('btn_theme').src = "img/" + sources[iterator];
document.getElementById('btn_save').src = "img/" + sources2[iterator];
enableEdit(themes[iterator]);
}
function changeTheme () {
createCookie();
if (iterator < sources.length-1) {
iterator++;
} else {
iterator = 0;
}
document.cookie = "theme=" + iterator + ";expires=Date.getTime() + 60 * 60 * 24 * 365 * 10;";
document.getElementById('btn_theme').src = "img/" + sources[iterator];
document.getElementById('btn_save').src = "img/" + sources2[iterator];
enableEdit(themes[iterator]);
onMouseEnter('btn_theme');
}
function bold() {
textfield.document.execCommand("bold", false, null);
}
function italic() {
textfield.document.execCommand("italic", false, null);
}
function underline() {
textfield.document.execCommand("underline", false, null);
}
function changeFontSize (amount) {
font_size += amount;
textfield.document.body.style.fontSize = font_size + "px";
}
function onMouseEnter(id) {
mouseObj = id;
if (mouseObj != 'btn_theme' && mouseObj != 'btn_save') {
document.getElementById(mouseObj).style.color = color_hover;
} else {
document.getElementById(mouseObj).style.filter = "brightness(" + brightness + "%)";
}
}
function onMouseLeave(id) {
mouseObj = null;
}
setInterval(function() {
var isBold = textfield.document.queryCommandState("Bold");
var isItalic = textfield.document.queryCommandState("Italic");
var isUnderlined = textfield.document.queryCommandState("Underline");
if (isBold == true && mouseObj == null) {
document.getElementById("btn_bold").style.color = color_button_dark;
} else if (isBold == false && mouseObj == null) {
document.getElementById("btn_bold").style.color = color_button_light;
}
if (isItalic == true && mouseObj == null) {
document.getElementById("btn_ita").style.color = color_button_dark;
} else if (isItalic == false && mouseObj == null) {
document.getElementById("btn_ita").style.color = color_button_light;
}
if (isUnderlined == true && mouseObj == null) {
document.getElementById("btn_und").style.color = color_button_dark;
} else if (isUnderlined == false && mouseObj == null) {
document.getElementById("btn_und").style.color = color_button_light;
}
if (mouseObj != 'btn_plus') {
document.getElementById("btn_plus").style.color = color_button_dark;
}
if (mouseObj != 'btn_minus') {
document.getElementById("btn_minus").style.color = color_button_dark;
}
if (mouseObj != 'btn_theme') {
document.getElementById("btn_theme").style.filter = "brightness(100%)";
}
if (mouseObj != 'btn_save') {
document.getElementById("btn_save").style.filter = "brightness(100%)";
}
},10);
PHP for saving the note
<?php
require("dbconnect.php");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL:" . mysqli_error();
}
if (isset($_POST["posttext"]) && !empty($_POST["posttext"])) {
$content = $_POST['posttext'];
$content = mysqli_real_escape_string($connection, $_POST["posttext"]);
$insert = "INSERT INTO content (text) VALUES ('$content')";
mysqli_query($connection, $insert);
$id = mysqli_insert_id($connection);
}
?>

you can use jquery ...
$(document).ready(function(){
$(".textfield").keyup(function() {
$("#btn_save").css("opacity", 1);
});
});

Okay, I fixed the problem. Apparently Firefox needs $(document).ready() to properly function for keypress events (haven't tested other events).
So your code should be:
$(document).ready(function(){
$(".textfield").contents().keyup(function(evnt) {
document.getElementById("btn_save").style.opacity = "1";
saved = false;
});
});
Instead of:
$(".textfield").contents().keyup(function(evnt) {
document.getElementById("btn_save").style.opacity = "1";
saved = false;
});
As I already said this is a problem that only occured in Firefox AFAIK.
This code works in Chrome, Firefox, Opera, Edge and Internet Explorer as of time of writing this answer.

I had a similar problem.
The mobile keyboards (in Firefox) don't emit keyup, keydown and keypress events.
So, I met the Text Composition events.
Something like this:
myInput = document.getElementById('myInput');
myInput.addEventListener('compositionupdate', (event) => {
setTimeout(() => {
applyFilter(event)
});
})
The setTimeOut was necessary to wait input value receipt the keyboard value before call my function.

Related

Images not showing up in Javascript

This is supposed to be a dice game where 2 people click to roll dice and they add what they get until they reach the goal. Their score resets if they roll over 9 though. Images of dice are supposed to pop up and show what they rolled. I know the images are not on here but it still shows that there should an image there with the error symbol. I am having trouble with the second image not showing up which should come from the SetPic2 function. Any help would be appreciated. Also, the PASS buttons are supposed the pass the person's turn to the other player but the main problem is the images.
//console.log("file loaded");
//var p1Button = document.getElementById("p1");
var p1Button = document.querySelector("#p1");
var p2Button = document.querySelector("#p2");
var P1Pass = document.querySelector("P1Pass");
var P2Pass = document.querySelector("P2Pass");
var setButton = document.querySelector("#set");
var resetButton = document.querySelector("#reset");
var diceImage = document.querySelector("img");
var diceImage2 = document.querySelector("img2");
var p1Total = document.querySelector("#p1score");
var p2Total = document.querySelector("#p2score");
var targetScore = document.querySelector("#tscore");
var newScore = document.querySelector("#newtarget");
var num = 0,
num2 = 0,
p1val = 0,
p2val = 0,
target;
var playgame = true;
target = Number(targetScore.textContent); //convert the string to num
p1Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p1val = p1val + num + num2;
p1Total.textContent = p1val;
setButton.disabled = true;
p1Button.disabled = true;
p2Button.disabled = false;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p1val = 0;
}
if (p1val >= target) {
playgame = false;
p1Total.classList.add("winner");
stopGame();
}
}
});
p2Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p2val = p2val + num + num2;
p2Total.textContent = p2val;
setButton.disabled = true;
p1Button.disabled = false;
p2Button.disabled = true;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p2val = 0;
}
if (p2val >= target) {
playgame = false;
p2Total.classList.add("winner");
stopGame();
}
}
});
/*P1Pass.addEventListener("click", function(){
p1Button.disabled= true;
p2Button.disabled = false;
});
P2Pass.addEventListener("click", function(){
p1Button.disabled = false;
p2Button.disabled = true;
});*/
setButton.addEventListener("click", function() {
targetScore.textContent = newScore.value;
target = Number(targetScore.textContent);
setButton.disabled = true;
newScore.disabled = true;
});
resetButton.addEventListener("click", function() {
p1Button.disabled = false;
p2Button.disabled = true;
p1Total.textContent = "0";
p2Total.textContent = "0";
targetScore.textContent = "25";
setButton.disabled = false;
newScore.disabled = false;
p1Total.classList.remove("winner");
p2Total.classList.remove("winner");
playgame = true;
p1val = 0;
p2val = 0;
target = 25;
});
function stopGame() {
p1Button.disabled = true;
p2Button.disabled = true;
setButton.disabled = true;
newScore.disabled = true;
}
function setPic(val) {
if (val == 1) {
diceImage.src = "1.png";
} else if (val == 2) {
diceImage.src = "2.png";
} else if (val == 3) {
diceImage.src = "3.png";
} else if (val == 4) {
diceImage.src = "4.png";
} else if (val == 5) {
diceImage.src = "5.png";
} else if (val == 6) {
diceImage.src = "6.png";
}
}
function setPic2(val2) {
if (val2 == 1) {
diceImage2.src = "1.png";
} else if (val2 == 2) {
diceImage2.src = "2.png";
} else if (val2 == 3) {
diceImage2.src = "3.png";
} else if (val2 == 4) {
diceImage2.src = "4.png";
} else if (val2 == 5) {
diceImage2.src = "5.png";
} else if (val2 == 6) {
diceImage2.src = "6.png";
}
}
.winner {
color: green;
background-color: yellow;
}
;
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap
.min.css" integrity="sha384-
Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="gamestyle.css">
<title>Dice Game</title>
</head>
<body>
<div class="container">
<br>
<h1> <span id="p1score">0</span> vs. <span id="p2score">0</span> </h1>
<br>
<p>Target-Score: <span id="tscore">25</span></p>
<br>
<button class="btn btn-success" id="p1"> Player One </button>
<button class="btn btn-warning" id="p2"> Player Two </button>
<br><br>
<button class="btn btn-secondary" id="P1Pass">PASS</button>
<button class="btn btn-secondary" id="P2Pass">PASS</button>
<br><br> New Target: <input type="number" id="newtarget">
<br><br>
<button class="btn btn-primary" id="set"> Set </button>
<button class="btn btn-danger" id="reset"> Reset </button>
<br><br>
<img src="">
<img src="">
</div>
<script src="gamefunction.js"></script>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-
J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min
.js" integrity="sha384-
Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.m
in.js" integrity="sha384-
wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
Your selector will not finding your second image element.
var diceImage2 = document.querySelector("img2");
You could give your images IDs and reference them directly:
HTML
<img id="die1" src="" />
<img id="die2" src="" />
JS
var diceImage1 = document.getElementById('die1');
var diceImage2 = document.getElementById('die2');

Javascript code produces errors when moved from inline to external file

I have a copy script built in to the page I am working on, and when the copy JS is inline, it works great, but as soon as I moved it external, it produces the following error:
copy.js:1 Uncaught TypeError: Cannot read property 'addEventListener' of null
I am unsure why because when inline there is no issues. Copy of the section code is:
<?php
$connect = mysqli_connect("localhost", "brandina_templat", "REMOVED", "brandina_templates");
$catresult = "SELECT * FROM categories";
$catquery = mysqli_query($connect,$catresult);
$catquery2 = mysqli_query($connect,$catresult);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Templates Sheet | Brandin Arsenault's</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/tabcontent.js"></script>
<link href="css/bootstrap.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<br />
<h1 align="center">Templates Sheet</h1>
<center><ul class="tabs">
<?php
if(!$catquery)
{
die('Invalid query: ' . mysql_error());
}
while($row = mysqli_fetch_array($catquery))
{
$number=$row['number'];
$tabname=$row['tabname'];
$catname=$row['catname'];
echo "<li class='tab-link' data-tab='$tabname'>$catname</li>";
}
?>
</ul>
<?php
if(!$catquery2)
{
die('Invalid query: ' . mysql_error());
}
while($row = mysqli_fetch_array($catquery2))
{
$number=$row['number'];
$tabname=$row['tabname'];
$catname=$row['catname'];
$result = "SELECT * FROM templates WHERE category=$number";
$query = mysqli_query($connect,$result);
echo "<div id='$tabname' class='tab-content'>
<table><center>";
$c = 0;
$n = 3;
if(!$query)
{
die('Invalid query: ' . mysql_error());
}
while($row = mysqli_fetch_array($query))
{
$id=$row['id'];
$longname=$row['longname'];
$shortname=$row['shortname'];
$text=$row['text'];
if($c % $n == 0 && $c != 0)
{
echo '</tr><tr>';
}
$c++;
echo "
<td>
<center><b>$longname</b></center><textarea id='$id' cols='25' rows='3'>$text</textarea><br /><button id='$shortname'>Copy</button>
</td>
<script>
var shortname = '$shortname';
</script>";
}
echo "</center></table></div>";
}
?>
<script src='js/copy.js'></script>
</center>
</div>
</body>
</html>
copy.js is:
document.getElementById(shortname).addEventListener('click', function() {
copyToClipboardMsg(document.getElementById('$id'), 'msg');
});
function copyToClipboardMsg(elem, msgElem) {
var succeed = copyToClipboard(elem);
var msg;
if (!succeed) {
msg = 'Copy not supported or blocked. Press Ctrl+c to copy.'
} else {
msg = 'Text copied to the clipboard.'
}
if (typeof msgElem === 'string') {
msgElem = document.getElementById(msgElem);
}
msgElem.innerHTML = msg;
setTimeout(function() {
msgElem.innerHTML = '';
}, 2000);
}
function copyToClipboard(elem) {
// create hidden text element, if it doesn't already exist
var targetId = '_hiddenCopyText_';
var isInput = elem.tagName === 'INPUT' || elem.tagName === 'TEXTAREA';
var origSelectionStart, origSelectionEnd;
if (isInput) {
// can just use the original source element for the selection and copy
target = elem;
origSelectionStart = elem.selectionStart;
origSelectionEnd = elem.selectionEnd;
} else {
// must use a temporary form element for the selection and copy
target = document.getElementById(targetId);
if (!target) {
var target = document.createElement('textarea');
target.style.position = 'absolute';
target.style.left = '-9999px';
target.style.top = '0';
target.id = targetId;
document.body.appendChild(target);
}
target.textContent = elem.textContent;
}
// select the content
var currentFocus = document.activeElement;
target.focus();
target.setSelectionRange(0, target.value.length);
// copy the selection
var succeed;
try {
succeed = document.execCommand('copy');
} catch(e) {
succeed = false;
}
// restore original focus
if (currentFocus && typeof currentFocus.focus === 'function') {
currentFocus.focus();
}
if (isInput) {
// restore prior selection
elem.setSelectionRange(origSelectionStart, origSelectionEnd);
} else {
// clear temporary content
target.textContent = '';
}
return succeed;
}
Thanks in advance!
The variable $shortname exists when you use the inline code, but when you move your code to external it doesn't exists anymore.
You can use:
<script>
var shortname = '$shortname';
</script>
<script src='js/copy.js'></script>
And in your copy.js file you should use:
document.getElementById(shortname).addEventListener('click', function() {
Otherwise - the javascript code is looking for element that it's id is $shortname, and you don't really have one with the value.

POST Json to PHP get VAR

i have a form like this:
<?php
include '../db/baza.php';
?>
<?php include 'vrh.php' ?>
<div id="stranica">
<div id="stranicaOkvir">
<form action="dodaj_sliku_obrada.php" method="POST" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend>Dodaj sliku</legend>
<?php $upit = "SELECT kategorija_ID, kategorija_naziv FROM kategorije ORDER BY kategorija_ID ASC";
$ispis = mysql_query($upit) or die(mysql_error());
$blok_ispis = mysql_fetch_assoc($ispis);
$ukupno = mysql_num_rows($ispis); ?>
<p><strong>Obavezno odaberite kategoriju kojoj slika pripada</strong></p>
<p> <select name="kategorija" id="kategorija">
<?php do { ?>
<option value="<?php echo $blok_ispis['kategorija_ID']; ?>"> <?php echo $blok_ispis['kategorija_naziv']; ?></option>
<?php } while ($blok_ispis = mysql_fetch_assoc($ispis)); ?>
<?php mysql_free_result($ispis);?>
</select>
</p>
<input type="file" id="file" name="file[]" required multiple>
<input type="submit" id="submit" name="submit" value="Dodaj sliku">
<div class="progresbar">
<span class="progresbar-puni" id="pb"><span class="progresbar-puni-tekst" id="pt"></span></span>
</div>
<div id="uploads" class="uploads">
Uploaded file links will apper here.
<script src="js/dodaj_Sliku.js"></script>
<script>
document.getElementById('submit').addEventListener('click',function(e){
e.preventDefault();
var f = document.getElementById('file'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files: f,
progressBar: pb,
progressText: pt,
processor: 'dodaj_sliku_obrada.php',
finished: function(data){
var uploads = document.getElementById('uploads'),
uspjesno_Dodano = document.createElement('div'),
neuspjelo_Dodavanje = document.createElement('div'),
anchor,
span,
x;
if(data.neuspjelo_Dodavanje.length){
neuspjelo_Dodavanje.innerHTML = '<p>Nazalost, sljedece nije dodano: </p>';
}
uploads.innerText = '';
uploads.textContent = '';
for( x = 0; x < data.uspjesno_Dodano.length; x = x + 1){
anchor = document.createElement('a');
anchor.href = '../slike/galerija/' + data.uspjesno_Dodano[x].file;
anchor.innerText = data.uspjesno_Dodano[x].name;
anchor.textContent = data.uspjesno_Dodano[x].name;
anchor.target = '_blank';
uspjesno_Dodano.appendChild(anchor);
}
for( x = 0; x < data.neuspjelo_Dodavanje.length; x = x + 1){
span = document.createElement('span');
span.innerText = data.neuspjelo_Dodavanje[x].name;
span.textContent = data.neuspjelo_Dodavanje[x].name;
neuspjelo_Dodavanje.appendChild(span);
}
uploads.appendChild(uspjesno_Dodano);
uploads.appendChild(neuspjelo_Dodavanje);
},
error: function(){
console.log('Ne radi!');
}
});
});
</script>
<script>
</script>
</div>
</fieldset>
</form>
</div>
</div>
<?php include 'dno.php' ?>
The .js looks like this
var app = app || {};
(function(o){
"use strict";
//Privatne metode
var ajax, getFormData, setProgress;
ajax = function(data){
var xmlhttp = new XMLHttpRequest(), uspjesno_Dodano;
xmlhttp.addEventListener('readystatechange', function(){
if(this.readyState === 4){
if(this.status === 200){
uspjesno_Dodano = JSON.parse(this.response);
if(typeof o.options.finished === 'function'){
o.options.finished(uspjesno_Dodano);
}
} else {
if(typeof o.options.error === 'function'){
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function(event){
var percent;
if(event.lengthComputable === true){
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source){
var data = new FormData(), i;
for(i = 0; i < source.length; i = i + 1){
data.append('file[]', source[i]);
}
data.append('ajax', true);
data.append('kategorija', o.options.kategorija);
return data;
};
setProgress = function(value){
if(o.options.progressBar !== undefined){
o.options.progressBar.style.width = value ? value + '%' : 0;
}
if(o.options.progressText !== undefined){
o.options.progressText.innerText = value ? value + '%' : '';
o.options.progressText.textContent = value ? value + '%' : '';
}
};
o.uploader = function(options){
o.options = options;
if(o.options.files !== undefined){
ajax(getFormData(o.options.files.files));
}
}
}(app));
On the process.php part i want to listen the option value from select
"<select name="kategorija" id="kategorija">"
on the process.php when i
<?php
$kategorija = $_POST['kategorija'];
echo echo $kategorija;
?>
i alwasy get a 0 value, so what i am doing wrong? The file[] processing is working fine, but can't get it to work with a addtional variable.
You don't need to echo echo $kategorija; It should be echo $kategorija; If this causes an issue, which it might, try var_dump($kategorija) to view the contents of the variable.
Also, you're including your js throughout the page, this should be refactored and included properly in the head. The php should not be in the form of the document, it should be contained outside and included like you are doing with '../db/baza.php'; Finally, look into using PDO to connect to your db.

Why drop down display first character in capital after dot

I make a drop down on pop up screen. I am able to make that drop down using jQuery mobile. I used dform plugin. Everything is working fine. But I have one issue my first character display in capital letter when I added bootstrap.min.css - why?
When I run my program without bootstrap.min.css, it works fine. But when I run with bootstrap.css, it give first letter capital after . . As I written in small. This problem is only in chrome browser. When I run in firefox it works perfectly.
Can you please explain why it is occurring?
Here is my code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<link href=" https://dl.dropboxusercontent.com/s/bbvcx2zc4ocuqzt/bootstrap.min.css?m=" rel="stylesheet" type="text/css" />
<link href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" rel="stylesheet" type="text/css" />
<link href=" https://dl.dropboxusercontent.com/s/hg36tk1m7rc4gnj/style.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<script src="https://rawgit.com/daffl/jquery.dform/master/dist/jquery.dform-1.1.0.js"></script>
</head>
<body>
<button id="test">test</button>
<div data-role="popup" data-dismissible='false' data-transition="flip" id="tabbedPopup" data-theme="a"><a href="#"
data-rel="back"
data-role="button"
data-theme="a"
data-icon="delete"
data-iconpos="notext"
class="ui-btn-right cross-border cross-border closePopUp_h button circleClass" >Close</a>
<div id="commandInfo"></div>
<div id="commandInfoheader" class="comandinfoheader"></div>
<div data-role="collapsible-set" data-theme="b" data-content-theme="b" id="tabbedSet" data-iconpos="left">
</div>
</div>
</body>
<script type="text/javascript">
$(function () {
$('#test').click(function(){
createCommandPopUpTabs("tc_2-cmd_1_VoiceCallAudioMosMO");
$("#tabbedPopup").popup("open");
})
});
function createCommandPopUpTabs(id) {
var tabsHeader = ["InputParameter"];
var header = "<h3 >hh</h3>";
var commmand = "VoiceCallAudioMosMO";
var button = '<button onclick="return submitCommand("' + id
+ '")" style="" class="donebtn common-button1">Save</button>';
//$("#commandInfo").append(header);
$("#commandInfo").append(button);
$("#commandInfoheader").html(header);
for ( var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>hhh</h3></div>";
var content = generateCommandTabContent(tabsHeader[i], id);
$("#tabbedSet").append(header);
$("#tabbedSet").find("#" + headerId).append(content);
$("#tabbedSet").collapsibleset("refresh");
$('input[name=direction]').parent().addClass('cleassr')
$("#tabbedSet").children(":first").collapsible( "expand" );
}
}
function generateCommandTabContent(name, id) {
var commandName = "VoiceCallAudioMosMO";
if (name == "InputParameter") {
var object = new window[commandName]();
var map = object.generateInputRequirment();
var formData = generateInputParamForm(map, id, status);
var form = $("<form />");
var dform = form.dform(formData);
return dform;
}
return null;
}
function VoiceCallAudioMosMO() {
COMMAND_NAME = "VoiceCallMos";
COMMAND_DISPLAY_NAME = "VoiceCallMOS";
this.map = {};
}
VoiceCallAudioMosMO.prototype.generateInputRequirment = function () {
if(typeof VoiceCallAudioMosMO.JSON!="undefined") {
var inputs = VoiceCallAudioMosMO.JSON.input;
for (var key in inputs) {
var inputField = inputs[key];
var inputParameterInfo = new InputParameterInfo();
for (var inputKey in inputField) {
inputParameterInfo[inputKey] = inputField[inputKey];
}
this.map[inputParameterInfo.name] = inputParameterInfo;
}
return this.map;
}
};
function InputParameterInfo() {
}
VoiceCallAudioMosMO.JSON = {
"commandName": "VoiceCallAudioMosMO",
"input": {
"refFileName": {
"displayDetail": "The reference file name to play in case of uplink channel",
"displayName": "Ref File Name",
"inputType": "SWITCH",
"name": "refFileName",
"inputValues": {
"USAReference.wav": "USAReference.wav",
"Reference.wav": "Reference.wav"
},
"value": "",
"unit": "NONE",
"required": false,
"visible": true
}
}
};
function generateInputParamForm(map, id, status) {
var formId = "form_" + id;
var formdata = {
elements : []
};
formdata.id = formId;
formdata.name = formId;
formdata.method = "post";
var div = {
html : []
};
div.type = "div";
div.class = "inputDiv";
div.caption = "<h3>Input Parameters</h3>";
var tabIndex = 1;
var arr = id.split("-");
var data = null;
for ( var key in map) {
var inputObj = map[key];
if (inputObj.visible==false && inputObj.required==false) {
continue;
}else {
var obj = createFormObject(inputObj);
}
//var obj = createFormObject(inputObj);
if(typeof data=="undefined"){
obj.value = inputObj["value"];
}else if (data != undefined && data.hasOwnProperty(inputObj["name"])) {
obj.value = data[inputObj["name"]];
}
/*if (data != undefined && data.hasOwnProperty(inputObj["name"])) {
obj.value = data[inputObj["name"]];
} else if (inputObj.hasOwnProperty("value")) {
obj.value = inputObj["value"];
}*/
if (status == "view") {
obj.readonly = "true";
obj.disabled = "disabled";
}
obj.tabindex = tabIndex;
var objName = "VoiceCallAudioMosMO";
obj.onblur = "validateElement('" + objName + "', '" + formId + "','"
+ obj.name + "')";
var unit = {};
var fieldset = {
html : []
};
fieldset.type = "fieldset";
fieldset.caption = inputObj["displayName"];
fieldset.html.push(obj);
$("div > fieldset legend:contains('*')").each(function () {
$(this).html($(this).html().replace("*", "<span class='red'>*</span>"));
});
div.html.push(fieldset);
tabIndex++;
}
formdata.elements.push(div);
return formdata;
}
function createFormObject(inputObj) {
var obj = {};
if (inputObj.hasOwnProperty("inputType")) {
if (inputObj["inputType"] == "LIST") {
var list = inputObj["inputValues"];
obj.type = "select";
obj.options = list;
} else if (inputObj["inputType"] == "NUMBER") {
obj.type = "text";
} else if (inputObj["inputType"] == "SWITCH") {
var list = inputObj["inputValues"];
obj.type = "select";
obj.options = list;
} else {
obj.type = "text";
}
} else {
obj.type = "text";
}
if (!inputObj.hasOwnProperty("displayName")) {
obj.type = "hidden";
}
obj.id = inputObj["name"];
obj.name = inputObj["name"];
obj.required = inputObj["required"];
obj.placeholder = inputObj["placeholder"];
obj.classes = inputObj["class"];
obj.className = inputObj["class"];
obj.class = inputObj["class"];
obj.title= inputObj["displayDetail"];
return obj;
}
</script>
</html>
It display a drop down when you click button.Drop down Value USAReference.wav.here I written "w" in small but it display in capital.but when I remove this css
https://dl.dropboxusercontent.com/s/bbvcx2zc4ocuqzt/bootstrap.min.css?m=" rel="stylesheet" type="text/css" />
it show in small letter ? why ?
After a long research I found the solution own .there is a property
text-transform: capitalize written on 247 line Number bootstrap.css file.I remove that property.I am able to solve my problem

Toggle to open/close tabbed navigation

I am very new to jQuery/Javascript and have been trying to have a tabbed navigation menu closed on page load then open if clicked by the user. So far I haven't had any joy with editing the following file
function amshopby_start(){
$$('.block-layered-nav .form-button').each(function (e){
e.observe('click', amshopby_price_click_callback);
});
$$('.block-layered-nav .input-text').each(function (e){
e.observe('focus', amshopby_price_focus_callback);
e.observe('keypress', amshopby_price_click_callback);
});
$$('a.amshopby-more', 'a.amshopby-less').each(function (a){
a.observe('click', amshopby_toggle);
});
$$('span.amshopby-plusminus').each(function (span){
span.observe('click', amshopby_category_show);
});
$$('.block-layered-nav dt').each(function (dt){
dt.observe('click', amshopby_filter_show);
});
$$('.block-layered-nav dt img').each(function (img){
img.observe('mouseover', amshopby_tooltip_show);
img.observe('mouseout', amshopby_tooltip_hide);
});
$$('.amshopby-slider-param').each(function (item) {
param = item.value.split(',');
amshopby_slider(param[0], param[1], param[2], param[3], param[4], param[5], param[6]);
});
}
function amshopby_price_click_callback(evt) {
if (evt && evt.type == 'keypress' && 13 != evt.keyCode)
return;
var prefix = 'amshopby-price';
// from slider
if (typeof(evt) == 'string'){
prefix = evt;
}
else {
var el = Event.findElement(evt, 'input');
if (!Object.isElement(el)){
el = Event.findElement(evt, 'button');
}
prefix = el.name;
}
var a = prefix + '-from';
var b = prefix + '-to';
var numFrom = amshopby_price_format($(a).value);
var numTo = amshopby_price_format($(b).value);
if ((numFrom < 0.01 && numTo < 0.01) || numFrom < 0 || numTo < 0) {
return;
}
var url = $(prefix +'-url').value.gsub(a, numFrom).gsub(b, numTo);
amshopby_set_location(url);
}
function amshopby_price_focus_callback(evt){
var el = Event.findElement(evt, 'input');
if (isNaN(parseFloat(el.value))){
el.value = '';
}
}
function amshopby_price_format(num){
num = parseFloat(num);
if (isNaN(num))
num = 0;
return Math.round(num);
}
function amshopby_slider(width, from, to, max_value, prefix, min_value, ratePP) {
width = parseFloat(width);
from = parseFloat(from);
to = parseFloat(to);
max_value = parseFloat(max_value);
min_value = parseFloat(min_value);
var slider = $(prefix);
// var allowedVals = new Array(11);
// for (var i=0; i<allowedVals.length; ++i){
// allowedVals[i] = Math.round(i * to /10);
// }
return new Control.Slider(slider.select('.handle'), slider, {
range: $R(0, width),
sliderValue: [from, to],
restricted: true,
//values: allowedVals,
onChange: function (values){
this.onSlide(values);
amshopby_price_click_callback(prefix);
},
onSlide: function(values) {
var fromValue = Math.round(min_value + ratePP * values[0]);
var toValue = Math.round(min_value + ratePP * values[1]);
/*
* Change current selection style
*/
if ($(prefix + '-slider-bar')) {
var barWidth = values[1] - values[0] - 1;
if (values[1] == values[0]) {
barWidth = 0;
}
$(prefix + '-slider-bar').setStyle({
width : barWidth + 'px',
left : values[0] + 'px'
});
}
if ($(prefix+'-from')) {
$(prefix+'-from').value = fromValue;
$(prefix+'-to').value = toValue;
}
if ($(prefix + '-from-slider')) {
$(prefix + '-from-slider').update(fromValue);
$(prefix + '-to-slider').update(toValue);
}
}
});
}
function amshopby_toggle(evt){
var attr = Event.findElement(evt, 'a').id.substr(14);
$$('.amshopby-attr-' + attr).invoke('toggle');
$('amshopby-more-' + attr, 'amshopby-less-' + attr).invoke('toggle');
Event.stop(evt);
return false;
}
function amshopby_category_show(evt){
var span = Event.findElement(evt, 'span');
var id = span.id.substr(16);
$$('.amshopby-cat-parentid-' + id).invoke('toggle');
span.toggleClassName('minus');
Event.stop(evt);
return false;
}
function amshopby_filter_show(evt){
var dt = Event.findElement(evt, 'dt');
dt.next('dd').down('ol').toggle();
dt.toggleClassName('amshopby-collapsed');
Event.stop(evt);
return true;
}
function amshopby_tooltip_show(evt){
var img = Event.findElement(evt, 'img');
var txt = img.alt;
var tooltip = $(img.id + '-tooltip');
if (!tooltip) {
tooltip = document.createElement('div');
tooltip.className = 'amshopby-tooltip';
tooltip.id = img.id + '-tooltip';
tooltip.innerHTML = img.alt;
document.body.appendChild(tooltip);
}
var offset = Element.cumulativeOffset(img);
tooltip.style.top = offset[1] + 'px';
tooltip.style.left = (offset[0] + 30) + 'px';
tooltip.show();
}
function amshopby_tooltip_hide(evt){
var img = Event.findElement(evt, 'img');
var tooltip = $(img.id + '-tooltip');
if (tooltip) {
tooltip.hide();
}
}
function amshopby_set_location(url){
if (typeof amshopby_working != 'undefined'){
return amshopby_ajax_request(url);
}
else {
return setLocation(url);
}
}
document.observe("dom:loaded", function() { amshopby_start(); });
The element that I am trying to manipulate is contained in this file
<?php if($this->canShowBlock()): ?>
<div class="block block-layered-nav">
<div class="block-title">
<strong><span><?php echo $this->__('Shop By') ?></span></strong>
</div>
<?php echo $this->getStateHtml() ?>
<div class="block-content">
<?php if($this->canShowOptions()): ?>
<!-- <p class="block-subtitle">--><?php //echo $this->__('Shopping Options') ?><!--</p>-->
<ul id="narrow-by-list">
<li>
<?php $_filters = $this->getFilters() ?>
<?php foreach ($_filters as $_filter): ?>
<?php if($_filter->getItemsCount()): ?>
<div class="opt-row">
<dl class="opt-row">
<dt><?php echo $this->__($_filter->getName()) ?></dt>
<dd><?php echo $_filter->getHtml() ?></dd>
</dl>
</div>
<?php endif; ?>
<?php endforeach; ?>
</li>
</ul>
<script type="text/javascript">decorateDataList('narrow-by-list')</script>
<?php endif; ?>
<?php if ($this->getLayer()->getState()->getFilters()): ?>
<div class="actions"><?php echo $this->__('Clear All') ?></div>
<?php endif; ?>
</div>
</div>
<?php endif; ?>
When the page loads I woul like to have the tabbed navigation menus closed but toggable to open by the user... Can anyone assist please?
From the admin panel, you can make any of your filters closed by default:-
Catalog > Improved Navigation > Filters
Select the relevant filter and set 'Collapsed' to 'Yes'.

Categories