Text and cursor styles changed via JavaScript: browser compatibility problems - javascript

i have a navigation bar that uses JavaScript to track its state and to update text and cursor style attributes accordingly. This works as intended in Firefox 26.0, but not in Chrome 32.0.1700.76; in Chrome, it appears to do nothing. A short script that illustrates this is:
var foo = document.getElementById('foo');
var bar = document.getElementById('bar');
var foo_on = true;
function turn_on(x) {
x.style = "color: #42A6FF; cursor: pointer;";
x.onmouseover = function () { x.style = "color: #444444; cursor: pointer;"; };
x.onmouseout = function () { x.style = "color: #42A6FF; cursor: pointer;"; };
}
function turn_off(x) {
x.style = "color: #BBBBBB; cursor: default;";
x.onmouseover = null;
x.onmouseout = null;
}
function toggle(caller) {
if((foo_on && caller == 'bar') || (!foo_on && caller == 'foo')){ return; }
if(foo_on){
turn_off(foo);
turn_on(bar);
}
else{
turn_on(foo);
turn_off(bar);
}
foo_on = !foo_on;
}
function init() {
foo_on = true;
turn_on(foo);
turn_off(bar);
}
window.onload = init();
My document layout is:
<html>
<head>
<title>Test</title>
</head>
<body>
<div style='-moz-user-select: none; -webkit-user-select: none; -ms-user-select:none; user-select:none;' unselectable='on'>
<a id="foo" onclick="toggle('foo')"> FOO </a>
<a id="bar" onclick="toggle('bar')"> BAR </a>
</div>
<script> {code above} </script>
</body>
</html>
This is live at http://jsfiddle.net/TF9X7/. Why doesn't this work in Chrome (or what mistake is Firefox forgiving me for)?

Or do it right, and use classes …
I'm very new to JavaScript; could you elaborate or provide a reference?
Instead of setting the style values directly via JS, you define them in your CSS, using a certain class name – and then you set or remove that class name for the elements:
CSS:
a { color: #BBBBBB; cursor: default; }
a.on { color: #42A6FF; cursor: pointer; }
a.on:hover { color: #444444; };
JS:
function turn_on(x) {
x.className = "on";
}
function turn_off(x) {
x.className = "";
}
http://jsfiddle.net/TF9X7/2/

I changed some parts of your script. Instead off window.onload, use body onload (<body onload="Init()">). The browser first needs to render the DOM in order to capture the objects.
In the function Init(), I changed to capture the element again, because Chrome is returning null, and I changed how you set the properties of style, the correct is object.style.property.
<script>
var foo = document.getElementById('foo');
var bar = document.getElementById('bar');
var foo_on = true;
function turn_on(x) {
x.style.color = "#42A6FF";
x.style.cursor = "pointer";
x.onmouseover = function () {
x.style.color = "#444444";
x.style.cursor = "pointer";
};
x.onmouseout = function () {
x.style.color = "#42A6FF";
x.style.cursor = "pointer";
};
}
function turn_off(x) {
x.style.color = "#BBBBBB";
x.style.cursor = "default";
x.onmouseover = null;
x.onmouseout = null;
}
function toggle(caller) {
if((foo_on && caller == 'bar') || (!foo_on && caller == 'foo')){
return;
}
if(foo_on){
turn_off(foo);
turn_on(bar);
}
else{
turn_on(foo);
turn_off(bar);
}
foo_on = !foo_on;
}
function init() {
foo = document.getElementById('foo');
bar = document.getElementById('bar');
foo_on = true;
turn_on(foo);
turn_off(bar);
}
body.onload = init();
</script>
But I advise you to use the way of CBroe

Related

changing a Javascript image on event listener click

i have a Div holding an image with the id sunset that i want to add an onclick to to change its width from the CSS 25% to 100%
cannot see why my code is not working
var content = document.getElementById("sunset");
var first_click = true;
content.addEventListener("click", function () {
if (first_click) {
content.style.width = "100%";
}
else {
content.style.width = "25%";
}
});
CSS
#sunset{
width:25%
}
The first if statement doesn't check if the first_click var is true (assuming that is what you intend to do). Since it is empty it would return false and the else statement would run, keeping your image at 25%.
try this:
var content = document.getElementById("sunset");
var first_click = true;
content.addEventListener("click", function () {
if (first_click == true) {
content.style.width = "100%";
}
else {
content.style.width = "25%";
}
});
Have you tried adding height to your container ? This should work
var content = document.getElementById("sunset");
var first_click = true;
content.addEventListener("click", function () {
if (first_click) {
content.style.width = "100%";
first_click = false;
}
else {
content.style.width = "25%";
}
});
#sunset{
width:25%;
background: #000;
height: 200px;
}
<div id="sunset"></div>
The problem is that you're not toggling the first_click variable to true or false when the image is clicked. The code below fixes this by setting first_click = !first_click:
var content = document.getElementById("sunset");
var first_click = true;
content.addEventListener("click", function() {
if (first_click) {
content.style.width = "100%";
} else {
content.style.width = "25%";
}
first_click = !first_click;
});
#sunset {
width: 25%
}
<img id="sunset" src="https://dummyimage.com/150/f8f">

Can anybody help me out with my Darkmode?

I want do have a basic Darkmode linked to a key press. I'am a Beginner in JavaScript and i cannot get it to work. I want it like, you press a key, the Darkmode turns on with a Cookie over js-cookie, and I press the same Key again to turn off the Darkmode and delete the cookie. Can anybody help me?
There is my Code:
var elem = document.getElementById("folie");
window.addEventListener("keydown", checkKeyPress);
function checkKeyPress(key) {
let zahl = 1;
if (key.keyCode == "70") {
if (zahl == 1) {
zahl++
dark()
Cookies.set("Darkmode", "An");
}
if (zahl == 2) {
zahl--
Cookies.remove("Darkmode")
}
}
}
var DarkCookie = Cookies.get("Darkmode");
if (DarkCookie == 'An') {
dark();
}
function dark() {
var element = document.body;
element.classList.toggle("dark-mode");
}
Edit:
Ok i've got it:
let CookieDarkMode = false;
function toggleDarkMode() {
var element = document.body;
element.classList.toggle("dark-mode");
}
window.addEventListener("keydown", checkKeyPress);
function checkKeyPress(key) {
if (key.keyCode === 70) { //"F" has been pressed
CookieDarkMode = !CookieDarkMode;
console.log("Cookie Dark mode: " + CookieDarkMode);
toggleDarkMode();
if (CookieDarkMode) {
Cookies.set("Darkmode", "An");
}else {
Cookies.remove("Darkmode");
}
}
};
var DarkCookie = Cookies.get("Darkmode")
if (DarkCookie == 'An') {
CookieDarkMode = true;
toggleDarkMode();
}
You don't have to store a number. You can just get the previous cookie value with a boolean
let CookieDarkMode = false;
function toggleDarkMode() {
var element = document.body;
element.classList.toggle("dark-mode");
}
window.addEventListener("keydown", checkKeyPress);
function checkKeyPress(key) {
if (key.keyCode === 70) { //"F" has been pressed
CookieDarkMode = !CookieDarkMode;
console.log("Cookie Dark mode: " + CookieDarkMode);
toggleDarkMode();
}
};
body {
background-color: ghostwhite;
}
.dark-mode {
background-color: black;
color: white;
}
<body>
<p>Lorem Ipsum</p>
</body>
your problem is on your checkKeyPress function, you always check for the zahl value, but it will always start as 1.
for demostration purposes you are doing this basically:
function sum(){
let zahl = 1;
zahl++
console.log(zahl)
}
// you will never see a 3, because you are creating `zhl`
// in each call with a value of 1
sum();
sum();
sum();
sum();
therefore, each time you check for the zahl variable, it will be 1 and will always enter the if that turns on the darkmode.
the solution for your code would be to move the zahl variable outside the function scope:
let zahl = 1; // outside the function scope
var elem = document.getElementById("folie");
window.addEventListener("keydown", checkKeyPress);
function checkKeyPress(key) {
if (key.keyCode == "70") {
if (zahl == 1) {
zahl++
dark()
Cookies.set("Darkmode", "An");
}else if (zahl == 2) {
zahl--
Cookies.remove("Darkmode")
dark(); //you should call dark here as well to toggle to the other mode.
}
}
}
var DarkCookie = Cookies.get("Darkmode");
if (DarkCookie == 'An') {
dark();
}
function dark() {
var element = document.body;
element.classList.toggle("dark-mode");
}
note: it doesn't look like the best implementation, it would be easier to read if you use a boolean for the state of the mode or if you want multiple types, you can use the name as a key for each of the modes.

HTML + Javascript Button click again to undo

I was wondering how it is possible to make the button undo something too after clicking it. In my scenario just simple formatting of Text(Color,size etc), when you first click it, it formats the text as described in Javascript, but I would like to add a function, that when you click it again, that it undoes that.
`<script>
function myFunction(){
document.getElementById("demo").style.fontsize="25px";
document.getElementById("demo").style.color="#3AF702";
document.getElementById("demo").style.backgroundcolor="red";
}
</script>`
<button type="change" onclick="myFunction()">Change!</button>
I checked other articles already, which seemed to be related, but I did not get any smarter out of those, so my apologies in advance if it is a dup and thanks for your help!
<script>
var flag = true;
function myFunction(){
let el = document.getElementById("demo");
el.style.fontsize = flag ? "25px" : "";
el.style.color= flag ? "#3AF702" : "";
el.style.backgroundcolor=flag ? "red" : "";
flag = !flag;
}
</script>`
<button type="change" onclick="myFunction()">Change!</button>
The easiest way to do this is to add and remove a class
<style>
.change {
font-size: 25px;
color: #3AF702;
background-color="red"
}
</style>
<script>
var x = 0;
function myFunction() {
if (x == 0) {
document.getElementById("demo").classList.add("change");
x = 1;
} else {
document.getElementById("demo").classList.remove("change");
x = 0;
}
}
</script>
<button type="change" onclick="myFunction()">Change!</button>
Create an object that stores the initial values of your button and a variable which holds the state of it.
var state = 0;
var backup = {};
backup.fontSize = document.getElementById("demo").style.fontsize;
backup.color = document.getElementById("demo").style.color;
backup.background = document.getElementById("demo").style.backgroundcolor;
Now you can easily switch between the backup and the new values like this:
function myFunction() {
if (state == 0) {
document.getElementById("demo").style.fontsize = "25px";
document.getElementById("demo").style.color = "#3AF702";
document.getElementById("demo").style.backgroundcolor = "red";
state = 1;
} else {
document.getElementById("demo").style.fontsize = backup.fontSize;
document.getElementById("demo").style.color = backup.color;
document.getElementById("demo").style.backgroundcolor = backup.background;
state = 0;
}
}
var flag = true;
function myFunction(){
var x = document.getElementById("demo");
if (flag) {
x.style.backgroundColor = "red";
x.style.color="#3AF702";
x.style.fontSize="25px"
} else {
x.style.backgroundColor = "blue";
x.style.color="#dddddd";
x.style.fontSize="10px"
}
flag = !flag
}
function myFunction(){
demo.className = demo.className ? "" : "style"
}
.style {
font-size: 25px;
color: red;
background: blue;
}
<p id="demo">Hi!</p>
<button type="change" onclick="myFunction()">Change!</button>

Reset variable onclick event

I have a Javascript like given below, what it does is, it calls
doSomethingWithSelectedText
function which checks that if any text is selected (using function getSelectedObj).
getSelectedObj returns an object.
The problem is that div #text gets updated everytime some text is selected. And div #search opens the new google tab searching the highlighted/ selected text.
But it stops updating after that on any other selection.
document.onmouseup = doSomethingWithSelectedText;
document.onkeyup = doSomethingWithSelectedText;
function getSelectedObj() {
var selObj = {};
selObj.text = '';
if (typeof window.getSelection != "undefined") {
selObj.rect = window.getSelection().getRangeAt(0).getBoundingClientRect() ;
selObj.text = window.getSelection().toString();
} else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
// this block not used in new versions of chrome, mozilla and IE11
selObj.text = document.selection.createRange().text;
}
return selObj;
}
function doSomethingWithSelectedText(e) {
var selectedObj = getSelectedObj();
if (selectedObj.text) {
document.querySelector('#popup').style.display = 'block';
document.querySelector('#popup').style.top = e.clientY - 40;
document.querySelector('#popup').style.left = e.clientX + 20;
document.querySelector('#text').innerHTML = selectedObj.text;
document.querySelector('#search').addEventListener('click', function (e) {
window.open('https://www.google.com/search?q=' + selectedObj.text);
});
}
else {
document.querySelector('#popup').style.display = 'none';
selectedObj.text = '';
}
}
May be it is because of the addEventlistener is defined inside if () of the mouseup event. And it does not get updated. I don't know how to handle this.
index.html
<div id="popup">
<div id ="text"></div>
<div id="search" class="fa fa-search"></div>
<div id="save" class="fa fa-file"></div>
</div>
styles.css
#popup{
display: none;
background-color: orange;
color: white;
position: absolute;
z-index: 1000;
width:100px;
height: 50px;
}
#search,#save {
display: inline-block;
padding: 15px;
font-size: 20px;
}
You should indeed put the event handler outside of your function, as you will be stacking up handlers that all will be executed on the next search click.
Here is an update of your code with the changes marked with ***:
document.onmouseup = doSomethingWithSelectedText;
document.onkeyup = doSomethingWithSelectedText;
function getSelectedObj() {
var selObj = {};
selObj.text = '';
if (typeof window.getSelection != "undefined") {
// ***Additional safety to avoid runtime errors
if (window.getSelection().rangeCount) {
selObj.rect = window.getSelection().getRangeAt(0).getBoundingClientRect() ;
selObj.text = window.getSelection().toString();
}
} else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
// this block not used in new versions of chrome, mozilla and IE11
selObj.text = document.selection.createRange().text;
}
return selObj;
}
// ***Variable for retaining the search string
var searchStr = '';
// ***Capture mouseup instead of click, so we can prevent the document level
// handler to get called.
document.querySelector('#search').addEventListener('mouseup', function (e) {
window.open('https://www.google.com/search?q=' + searchStr);
return false; // ***Cancel bubbling to document.
});
function doSomethingWithSelectedText(e) {
var selectedObj = getSelectedObj();
if (selectedObj.text) {
console.log('text:' + selectedObj.text);
document.querySelector('#popup').style.display = 'block';
document.querySelector('#popup').style.top = e.clientY - 40;
document.querySelector('#popup').style.left = e.clientX + 20;
// ***Use textContent instead of innerHTML
document.querySelector('#text').textContent = selectedObj.text;
// ***Store search string to be used when launching search
searchStr = selectedObj.text;
} else {
document.querySelector('#popup').style.display = 'none';
}
}

Creating Dynamic Fullscreen and Minimize Div Functions

The screen displays 3 dynamically created and loaded divs. The problem I'm having is getting the resize to work when I try to make the divs go full screen. (Click the front button and the 2nd on the back). When using the select option on top, the resize works perfectly, but the fullscreen does not have the same effect.
This is my plunkr: http://plnkr.co/edit/qYxIRjs6KyNm2bsNtt1P
This is my current resize function:
for(i = 0; i<numOfDivs.length; i++){
var flipTarget = document.getElementById(flipDiv[i]);
addResizeListener(flipTarget, function() {
for(j = 0; j<numOfDivs.length; j++){
var style = window.getComputedStyle(flipTarget);
divWidth = parseInt(style.getPropertyValue('width'), 10);
divHeight = parseInt(style.getPropertyValue('height'), 10);
width = divWidth - margin.left - margin.right;
height = divHeight - margin.top - margin.bottom;
document.getElementById(frontDivNames[j]).innerHTML = '<span style="font-size: 40px; font-family:icons; cursor:pointer" id="flip" onclick="flipper(\''+flipperDivNames[j]+'\')"></span>';
makeTestGraph();
makeSliderGraph();
};
});
}
Any help on hiding all the other divs and making them reappear later would also be greatly appreciated. This has taken a few days of work and I have gotten almost nowhere despite rewriting the code several times.
Thanks for the help.
Is there something wrong with the javascript fullscreen api???
<script>
var fullscreen;
SetFullscreen = function DetectFullscreen(el){
DesktopFullScreen = function ToggleFullScreen(el){
function cancelFullScreen(el) {
if (window.document.exitFullscreen) {
window.document.exitFullscreen();
} else if (window.document.webkitExitFullscreen) {
window.document.webkitExitFullscreen();
} else if (window.document.mozCancelFullScreen) {
window.document.mozCancelFullScreen();
} else if (window.document.msExitFullscreen) {
window.document.msExitFullscreen();
}
return undefined;
}
function requestFullScreen(el) {
// Supports most browsers and their versions.
var requestMethod = document.getElementById(el).requestFullScreen || document.getElementById(el).webkitRequestFullScreen || document.getElementById(el).mozRequestFullScreen || document.getElementById(el).msRequestFullscreen;
if (requestMethod) { // Native full screen.
requestMethod.call(document.getElementById(el));
} else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
return true;
}
if (fullscreen){
fullscreen = cancelFullScreen(el);
}
else{
fullscreen = requestFullScreen(el);
}
}
MobileFullScreen = function ToggleFullScreen(el){
function cancelFullScreen(el) {
document.getElementById("fullscreenstyle").innerHTML="";
return undefined;
}
function requestFullScreen(el) {
document.getElementById("fullscreenstyle").innerHTML="#"+el+" {position:fixed;top:0px;left:0px;width:100%;height:100%;}";
return true;
}
if (fullscreen){
fullscreen = cancelFullScreen(el);
}
else{
fullscreen = requestFullScreen(el);
}
}
if( navigator.userAgent.match(/mobile/i)){
MobileFullScreen(el);
}
else{
DesktopFullScreen(el);
}
}
</script>
<style>
div{background:white;}
</style>
<style id="fullscreenstyle">
</style>
<div id="fullscreen" onclick="SetFullscreen(this.id)">hello</div>
Following on from your comments are you looking for something like this?
<script>
function cancelFullScreen(el) {
document.getElementById("fullscreenstyle").innerHTML="";
selectedElement = document.getElementById(el);
selectedElement.setAttribute("onclick","requestFullScreen(this.id)");
document.body.innerHTML=bodysave;
return undefined;
}
function requestFullScreen(el) {
document.getElementById("fullscreenstyle").innerHTML="#"+el+" {background:pink;position:fixed;top:0px;left:0px;width:97%;height:97%;}";
selectedElement = document.getElementById(el);
bodysave = document.body.innerHTML;
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
document.body.appendChild(selectedElement);
selectedElement.setAttribute("onclick","cancelFullScreen(this.id)");
return true;
}
</script>
<style>
div{background:white;}
</style>
<style id="fullscreenstyle">
</style>
<div id="fullscreen" onclick="requestFullScreen(this.id)">hello</div>
<div id="fullscreen2" onclick="requestFullScreen(this.id)">hello</div>
<div id="fullscreen3" onclick="requestFullScreen(this.id)">hello</div>

Categories