JavaScript hide and show toggle, hide DIV - javascript

For the following example, how would I start the page off by hiding the 'divToToggle' DIV as it is currently showing on default? I do not want to use 'display:none;' outside of the script for accessibility reasons. How do you hide the 'divToToggle' within the script on startup?
Thanks.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>JavaScript hide and show toggle</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
</head>
<body>
<script>
function toggleAndChangeText() {
$('#divToToggle').toggle();
if ($('#divToToggle').css('display') == 'none') {
$('#aTag').html('[+] Show text');
}
else {
$('#aTag').html('[-] Hide text');
}
}
</script>
<br>
<a id="aTag" href="javascript:toggleAndChangeText();">[-] Hide text</A>
<div id="divToToggle">Content that will be shown or hidden.</div>
</body>
</html>

Just use the hide function inside a document.ready function
$(function(){
$('#divToToggle').hide();
});

Just use jQuery, since you're already using it (and this way doesn't prevent non-JS users from seeing the element):
function toggleAndChangeText() {
$('#divToToggle').toggle();
if ($('#divToToggle').css('display') == 'none') {
$('#aTag').html('[+] Show text');
}
else {
$('#aTag').html('[-] Hide text');
}
}
$('#divToToggle').hide();
// the rest of your script(s)...
Also, a minor update to your toggle function:
function toggleAndChangeText() {
// because you're accessing this element more than once,
// it should be cached to save future DOM look-ups
var divToToggle = $('#divToToggle');
divToToggle.toggle();
// You're not changing the HTML, just the text, so use the
// appropriate method (though it's a *minor* change)
$('#aTag').text(function() {
// if the element is visible change the text to
// '...hide...'; if not, change the text to '...show...'
return divToToggle.is(':visible') ? '[-] Hide text' : '[+] Show Text';
});
}
References:
hide().
is().
text().
:visible selector.

Related

Apply class to button which execCommand on contentEditable div

Is there a built in way of keeping a button active when it execute a execCommand on a content editable div ?
example :
<input type="button" onclick="doRichEditCommand('bold');" value="B"/>
function doRichEditCommand(command){
document.execCommand(command, null, false);
}
I'd like my button to remain active when the carret is within something where document.execCommand(command, null, false); has been applied. I suppose it's doable by checking the parent elements but if there is a built in way it would be better.
In other words I'd like my bold button to be orange when the carret is somewhere which should be bold.
It's doable, but it's really annoying.
Every time the contenteditable changes you call document.queryCommandState() to find the state of the text where the caret is, and then update the button class to match. So something like:
let div = document.getElementById("myContentEditable");
div.oninput = () => {
if (document.queryCommandState('bold')) {
console.log("bold!");
} else {
console.log("not bold.");
}
return false;
};
From there you can apply or remove a style from your bold button to indicate whether the cursor's in a bold section or not. Repeat for the other styles.
The annoying part is that you need to update the button state on several different events. This seems fairly exhaustive to me:
div.oninput = div.onselect = div.onchange = div.onkeyup = eventhandler;
...but I could be wrong.
<head>
<script type="text/javascript">
var editorDoc;
function InitEditable () {
var editor = document.getElementById ("editor");
editorDoc = editor.contentWindow.document;
var editorBody = editorDoc.body;
// turn off spellcheck
if ('spellcheck' in editorBody) { // Firefox
editorBody.spellcheck = false;
}
if ('contentEditable' in editorBody) {
// allow contentEditable
editorBody.contentEditable = true;
}
else { // Firefox earlier than version 3
if ('designMode' in editorDoc) {
// turn on designMode
editorDoc.designMode = "on";
}
}
}
function ToggleBold () {
editorDoc.execCommand ('bold', false, null);
}
</script>
</head>
<body onload="InitEditable ();">
First, write and select some text in the editor.
<br />
<iframe id="editor" src="editable.htm"></iframe>
<br /><br />
You can toggle the bold/normal state of the selected text with this button:
<br />
<button onclick="ToggleBold ();">Bold</button>
</body>
editable.html:
<!DOCTYPE html>
<html>
<head>
<title>Editable content example</title>
<meta charset="utf-8" />
</head>
<body>
Some text in the editor.
</body>
</html>
some possible solution here: execCommand method examples
This is what I achieved:
JS
function format(command) {
document.execCommand(command, false);
const button = document.getElementById(command);
button.classList.toggle("button--active");
}
HTML
<button id="bold" onclick="format(this.id)">Bold</button>
SCSS
button {
//Whatever you want
&--active {
//Whatever you want
}
}
However, it works for general writing. If you select text and apply an effect, the button will be kept active.

Adding and removing a tag on function call

I need to change the color of a specific word inside a text of an element. I tried adding and removing span tags to change the style of the word, but I can't remove it after. Here's the code I tried
function changeColor(unit){
document.getElementsByClassName("label")[0].innerHTML=document.getElementsByClassName("label")[0].innerHTML.replace('/<span id="highlighted">(.*)<\/span>/g','$1');
document.getElementsByClassName("label")[0].innerHTML=document.getElementsByClassName("label")[0].innerHTML.replace(unit,'<span id="highlighted">' + unit + '</span>');
}
The text looks like this "°C,kW/h,cm".
What is happening right now is everytime the function is called, span tags are added but never removed. How can I achieve this with Javascript/JQuery?
Desired behavior :
When the function is called with say "cm" as parameter. I want the string to become "°C,kW/h,<span id=highlighted>cm</span>". Now if the function is called again with "kW/h", I want the string to become "°C,<span id=highlighted>kW/h</span>,cm"
With jQuery you can use .unwrap():
Try:
$(document).ready(function(){
$("label span").contents().unwrap()
});
label {color:green}
#highlighted{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<label>°C,<span id=highlighted>kW/h</span>,cm</label>
Change
.replace('/<span id="highlighted">(.*)<\/span>/g','$1')
to
.replace(/<span id="highlighted">(.*)<\/span>/g,'$1')
The first one is a string, the second one a RegEx and you need the latter.
See how replace works. The first argument is either a string or a RegEx.
Adding my no-jQuery solution:
Make 3 spans (s1, s2, s3)
Change the color style depending on the unit input
And so:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script>
function changeColor(unit) {
var allUnits = [ '°C', 'kW/h', 'cm' ];
for (var i = 0; i < allUnits.length; i++) {
if (unit == allUnits[i])
document.getElementById('s'+(i+1)).style = 'color:#00FFFF';
else
document.getElementById('s'+(i+1)).style = 'color:#000000';
}
}
document.addEventListener("DOMContentLoaded", function(event) {
changeColor('kW/h');
});
</script>
</head>
<body>
<span id="s1">°C</span>,<span id="s2">kW/h</span>,<span id="s3">cm</span>
</body>
</html>

Transfer pop up HTML content inside JS file

I have this working pop up HTML code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head profile="http://gmpg.org/xfn/11">
<title>PopUp</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" media="all" href="style.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.popup.min.js"></script>
<script type="text/javascript">
jQuery(function () {
jQuery().popup();
});
</script>
</head>
<body>
Show popup
<div id="popup-box">
This is the pop up content. The quick brown fox jumps over the lazy dog.
</div>
</body>
</html>
The actual pop up content is inside the:
<div id="popup-box">
</div>
Is it possible to transfer the pop up HTML content (..) to my JS file? Actually inside the jQuery function click event? Example:
jQuery( document ).ready( function($) {
$('#triggerforpopup').live('click',(function() {
//launch the pop code to HTML
}));
});
So after the click event, the JS will simply pop it out, but it's originating inside the JS file not an HTML hidden on an existing content.
The reason is that I'm writing a Wordpress plugin and it would be convenient to have all this information in a JS file. I don't want putting additional HTML code in the existing template content which is hidden by default.
Thanks for helping.
UPDATE: I have created a fiddle for this one here: http://jsfiddle.net/codex_meridian/56ZpD/3/
(function (a) {
a.fn.popup = function (b) {
var c, d = [self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft, self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop];
a("body").append(c = a('<div id="popup-overlay"></div>')), _init = function () {
_add_overlay(), _add_buttons(), a("#popup-box #popup-content").css("max-height", a(window).height() - 400), a(window).on("resize", function () {
a("#popup-box #popup-content").css("max-height", a(window).height() - 400)
})
}, _add_overlay = function () {
c.css({
opacity: .85,
position: "absolute",
top: 0,
left: 0,
width: "100%",
"z-index": 99999,
display: "none",
height: a(document).height()
})
}, _show_overlay = function () {
c.is(":visible") || c.fadeIn("fast")
}, _hide_overlay = function () {
c.is(":visible") && c.hide()
}, _add_buttons = function () {
a("a[rel=popup-close]").click(function () {
return _hide_box(), !1
}), a("a[rel=popup-open]").click(function () {
return _show_box(), !1
})
}, _show_box = function () {
if (!a("#popup-box").is(":visible")) {
_show_overlay(), a("#popup-box").fadeIn("fast");
var b = a("html");
b.data("scroll-position", d), b.data("previous-overflow", b.css("overflow")), b.css("overflow", "hidden"), window.scrollTo(d[0], d[1])
}
}, _hide_box = function () {
if (a("#popup-box").is(":visible")) {
var b = a("html"),
c = b.data("scroll-position");
b.css("overflow", b.data("previous-overflow")), window.scrollTo(c[0], c[1]), _hide_overlay(), a("#popup-box").hide()
}
}, _init()
}
})(jQuery)
You can write your content directly in your JS as a string and then use the innerHTML property of elements to set their value. You can do this in pure JS as follows.
var popup = document.getElementById("popup-box");
var html = "This is the pop up content. The quick brown fox jumps over the lazy dog.";
popup.innerHTML = html;
And you can do this in jQuery as follows:
$('#triggerforpopup').on('click', function() {
$("#popup-box").html(html); // Where html is a variable containing your text.
});
Note: You can write in HTML tags and the like in your html string and they will be rendered as you would expect on the page. You are not limited to plaintext.
Note: live has been deprecated in jQuery as of jQuery 1.7. It has been replaced with on. See http://api.jquery.com/live/ and http://api.jquery.com/on/.
If you want to include everything in the JavaScript as mentioned in the comments, you can do this:
var popup = document.createElement("div");
popup.id = "popup-box";
popup.innerHTML = "your html here";
document.getElementById("parent element id").appendChild(popup);
What this does is create a new div element, set its id and then append it as the child element of the parent of your choice. You could just do a plain insert of the HTML string into another element, but by creating an element here you have a bit more flexibility regarding its placement.
use
var popupHtml = $('<div>This is the pop up content. The quick brown fox jumps over the lazy dog.</div>');
popupHtml.popup();
I found lots of issues in the popup plugin you have used. Fixed them to make it working. Have a look http://jsbin.com/oyamiy/6/watch

Multiple modes Codemirror

I want my TextArea to be able to support multiple CodeMirror modes. For now I want it to support json and xml. Is this possible?
Also, is it possible to automatically detect whether the user placed json or xml in the area?
Thanks.
CodeMirror actually has an example very close to what you are looking for here.
Here is a more specific example that does what you want.
Create a CodeMirror instance.
When the content changes we determine if we should switch modes.
The logic I put in for determining what mode you are in is very simplistic and can be refactored to support as robust a check as you deem appropriate for either mode. (Regex is good for complex checking if you want to get fancy...that is the only reason I used it even in my simple example) Currently, my example code just checks for any content where the first non-space character is "<" thus indicating xml mode. When deciding to switch back it just checks that the first non-space character is not "<" and that it is not blank (in case the user just deleted everything to start over with more xml).
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Code Mirror Example</title>
<script src="lib/codemirror.js"></script>
<link rel="stylesheet" href="lib/codemirror.css">
<script src="mode/javascript/javascript.js"></script>
<script src="mode/xml/xml.js"></script>
<style type="text/css">.CodeMirror{border:1px solid black;}</style>
</head>
<body>
<div><span>Mode: </span><span id="modeType">JSON</span></div>
<textarea class='codeEditor'></textarea>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function determineCodeMirrorType(cm)
{
if (cm.getMode().name == 'javascript')
{
checkAndSwitchToXML(cm, cm.getValue());
}
else if (cm.getMode().name == 'xml')
{
checkAndSwitchToJSON(cm, cm.getValue());
}
}
function checkAndSwitchToXML(cm, val)
{
if (/^\s*</.test(val))
{
cm.setOption("mode", "xml");
$('#modeType').html("XML");
}
}
function checkAndSwitchToJSON(cm, val)
{
if (!/^\s*</.test(val) && val.match(/\S/))
{
cm.setOption("mode", "javascript");
$('#modeType').html("JSON");
}
}
function buildCMInstance(mode, value)
{
var cm = CodeMirror.fromTextArea($('.codeEditor')[0], {
mode:mode,
value:value,
lineNumbers:true,
onChange:function(cmInstance){
determineCodeMirrorType(cmInstance);
}
});
return cm;
}
$(document).ready(function(){
//mode changing demo: "http://codemirror.net/demo/changemode.html";
var cm = buildCMInstance("javascript");
});
</script>
</body>
</html>

Making JS buttons that toggle their image on click

I am doing something like this-
http://www.w3schools.com/html5/tryit.asp?filename=tryhtml5_video_js_prop
but I want to replace the buttons with images that toggle to another image when clicked. In other words, the Play button will change to a Pause button.
There are many tutorials that show how to do this with only one button but as soon as I add more buttons, the new ones don't work.
Any help appreciated!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<script type="text/javascript">
function changeIt()
{
var theImg = document.getElementsByTagName('img')[0].src;
var x = theImg.split("/");
var t = x.length-1;
var y = x[t];
if(y=='btnPlay.gif')
{
document.images.PlayOrPause.src='btnPause.gif'
}
if(y=='btnPause.gif')
{
document.images.PlayOrPause.src='btnPlay.gif'
}
}
</script>
<img src='btnPause.gif' name='PlayOrPause' border='0' />
Try this using input type image
HTML
<input type="image" src="play.png" class="play" onclick="toggle(this);"/>
CSS
.play, .pause {width:100px;height:100px;}
​
JS
function toggle(el){
if(el.className!="pause")
{
el.src='pause.png';
el.className="pause";
}
else if(el.className=="pause")
{
el.src='play.png';
el.className="play";
}
return false;
} ​
A fiddle is here.
​
swap : function(id) {
var e = document.getElementById(id);
e.className = (e.className == 'image1')
? 'image2'
: 'image1';
}
You can just make a function that checks the current class and switches it. This is the simplest example in which the 2 classes have different background images. The rest of the logic you could handle in a different function that manages the player's 'state' of playing, paused, etc.

Categories

Resources