I've made a bunch of JavaScript functions to show, hide and populate various elements on a zooming menu. All seem to working except for one which I need the function to only run if a CSS setting is a specific value (width of 195%). I am very new to JavaScript so there may be more than one issue here.
<script>
function zoomShowF2() {
var widthNow = document.getElementById('svg1').style.width;
if widthNow = '195%' {
document.getElementById('zoomTitle').style.display = 'flex';
else
document.getElementById('zoomTitle').style.display = 'none';
}}</script>
You need to use comparison operators write the if statement as follows
if (widthNow == '195%') {
as the single = is assigning the value not comparing it
There are a few issues with your syntax:
function zoomShowF2() {
var widthNow = document.getElementById('svg1').style.width;
if (widthNow === '195%') {
document.getElementById('zoomTitle').style.display = 'flex';
} else {
document.getElementById('zoomTitle').style.display = 'none';
}
}
Thanks everyone. It works now with a combination of the changes suggested. I assume my curly braces are all in 'tidy' positions?
EDIT. I've adjusted the curly brace positions to as per Ed's layout.
Thanks all!
Your code does not called when the element changes it size or width. You must put all your code inside window.onresize event.
var displayOutput = document.getElementById("display-option");
function reportWindowSize() {
displayOutput.text = document.getElementById("element-to-check").style.width;
}
window.onresize = reportWindowSize;
<p id="element-to-check">Resize the browser window to fire the <code>resize</code> event.</p>
<p>Display: <span id="display-option"></span></p>
Related
I made CSS animations and buttons to play the animations and use add and remove classes to play each motion. I didn't use a toggle because if I use a toggle, it mixes with other buttons.
I've seen many CSS animations that didn't use js at all.
Is there any way to reduce my js code and simplify it?
Here is the code-
playbtn.addEventListener("click", function (e) {
e.preventDefault;
ball.style.display = "block";
bowl.style.display = "none";
ball.classList.remove("ball-move");
ball.offsetWidth = ball.offsetWidth;
ball.classList.add("ball-move");
document.getElementById('dFace').className = '';
dFace.offsetWidth = dFace.offsetWidth;
dFace.classList.add("p-head-move");
document.getElementById('ear').className = '';
ear.offsetWidth = ear.offsetWidth;
ear.classList.add("lean");
document.getElementById("mouthid").className = '';
mouth.offsetWidth = mouth.offsetWidth;
mouth.classList.add("mouth-move");
}, false);
I think you have to read about Animation play state api, that will reduce your code.
Doc Link!
1, From your code, I assume that bowl, ball, dFace, ear and mouth are all HTMElement that have already assigned with a value from document.getElementById. So, you may not have to get the HTMLElement again in this functions.
2, You may not need to assign the value for offsetWidth as it is a read-only property as described in https://www.w3schools.com/jsref/prop_element_offsetwidth.asp. You can remove those lines.
You might be missing () for e.preventDefault
I will suggest the followings:
playbtn.addEventListener("click", function (e) {
e.preventDefault();
ball.style.display = "block";
bowl.style.display = "none";
ball.classList.remove("ball-move");
ball.classList.add("ball-move");
dFace.className = '';
dFace.classList.add("p-head-move");
ear.className = '';
ear.classList.add("lean");
mouth.className = '';
mouth.classList.add("mouth-move");
}, false);
Also, the action on dFace, ear and mouth are similar, so you may wrap it in a function call restartAnimation to further reduce duplications of your code.
const restartAnimation = (ele, className) => {
ele.className = '';
ele.classList.add(className);
}
playbtn.addEventListener("click", function (e) {
e.preventDefault();
ball.style.display = "block";
bowl.style.display = "none";
ball.classList.remove("ball-move");
ball.classList.add("ball-move");
restartAnimation(dFace, "p-head-move")
restartAnimation(ear, "lean")
restartAnimation(mouth, "mouth-move")
}, false);
You should include your CSS in your post as well! But I think you could avoid the restartAnimation instances you have by using animation-iteration-count: infinite; (if you are trying to make your animations loop, for example) in the CSS selector for the animated parts. I would recommend looking into the CSS animation documentation here as it's very clear! Good luck!
So I have written this clickDisplay function that displays certain elements on click, it works fine, yes, but obviously I needed a feature that would hide all the other elements, because they are supposed to be displayed in the same field, so right now they kind stack on top of eachother
this is what I came up with, but it sorta doesn't work and I don't know why
const pages = ['watch','chars','seasons','songs']
function clickHide(element){
document.getElementById(element).style.display = 'none';
}
function clickDisplay(element){
document.getElementById(element).style.display = 'block';
for(let x = 0 ; x < pages.length ; x++){
if (pages[x]!=element){clickHide(pages[x]);}
}
}
While it sounds like you solved your own problem, I started putting together code before you posted, so I'll throw it up here for you. :)
const pages = ['watch', 'chars', 'seasons', 'songs']
function clickHide (el) {
pages.forEach((pel) => {
setElement(pel, pel === el ? 'none' : 'block')
})
}
function setElement(el, attr) {
document.getElementById(el).style.display = attr
}
with the html having this:
onclick="clickHide('watch')" // or 'chars' 'seasons' or 'songs'
Oh wait, I don't know why but this suddenly works now. I only changed the placeholder text and refreshed the page
But I'm sure that this still is a stupid solution
My goal is to have a button (controlled by a javascript function) that would toggle the entire CSS on the website on and off. I thought this was a common practice and was surprised when I couldn't find a complete solution here or on the web.
Here is what I got.
$("#button").click(function() {
var css = (document.styleSheets[0].enabled = true);
if (css == true)
{
document.styleSheets[0].disabled = true;
css = (document.styleSheets[0].enabled = false);
}
else if (css == false)
{
document.styleSheets[0].disabled = false;
}
});
A simple Jquery function that targets the button by ID and performs an if test. I could've ommited the variable, but this way I am able to check the value easily in console.log. I am able to turn the CSS off, but not back on. The program doesn't even get to the else condition.
I am aware that the else if is not really appropriate, but with just else (and even just with another if condition) the function doesn't run at all.
Second option that I thought of, and which might be much easier is just dynamically changing the contents of the link href attribute, where the path to the css file is given.
But I am struggling to target the href element with Javascript.
This is a simple Boolean toggle so write it as a simple toggle
$("#button").click(function() {
var sheet = document.styleSheets[0];
sheet.disabled = !sheet.disabled;
});
As for why your code isn't working as is,
var css = (document.styleSheets[0].enabled = true);
// same as
var css;
document.styleSheets[0].enabled = true;
css = true;
which means
if (css == true)
// same as
if (true == true)
which always holds so you'll always follow this code path
Well, for one you need to loop through all of the stylesheets.
Also, you can save some lines of code by using a counter, then on each button click increment the counter and use the % modulo operator to turn that into a 1 or a 0, which you can then coerce a boolean from using !!.
var count = 0;
var sheets = document.styleSheets;
$("#button").click(function() {
for(var i in Object.keys(sheets)) sheets[i].disabled = !!(++count % 2);
});
.demo {
background: #888;
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="demo">Some Text</div>
<button id="button">Click It</button>
Your problem is that you are doing an assignment when you should be doing an equality check.
You have
var css = (document.styleSheets[0].enabled = true);
But you are really trying to do an equality check, i.e.,
var css = (document.styleSheets[0].enabled == true);
Notice the extra =. The single = does an assignment, so your current code is equivalent to this:
document.styleSheets[0].enabled = true
var css = document.styleSheets[0].enabled; // i.e., true
Because you set enabled to true, your if (css == true) condition is always satisfied, so your code always turns the CSS off and never turns it back on.
The fix, as Paul S. wrote in his answer, is just to toggle the value of document.styleSheets[0].disabled, as in:
$("#button").click(function() {
document.styleSheets[0].disabled = !document.styleSheets[0].disabled;
});
There's no need to set and track a new property enabled.
The issue seems to be that you are doing assignment, and not comparison, on this line:
var css = (document.styleSheets[0].enabled = true);
It should be
var css = (document.styleSheets[0].enabled == true);
Probably simpler, since you have a jquery tag on the question, to just do:
$stylesheets = $('link[rel="stylesheet"]');
$("#button").click(function() {
$stylesheets.attr('disabled', !$stylesheets.attr('disabled'));
});
If you want to modify every href in your DOM,
just use
$('a[href*=]').each(function () {
var $this = $(this);
$this.attr('href', $this.attr('href').replace();
});
I am sorry for this very basic question. I am very new to javascript and learning it.
I am stuck with one easy problem-
This is what i am trying to do-
I have a header that has some innertext
<h1 id="bd" onmouseover="fun1()" onmouseout="fun2()"> sample</h1>
I am chaging innerHTML of this header on mouseover like this-
function fun1()
{
document.getElementById("bd").innerHTML="a";
}
well on mouseout i do the same but for getting original innerHTML for this header tag.
function fun2()
{
document.getElementById("bd").innerHTML=document.getElementById("bd").innerHTML;
}
But onmouseout function shows me changed innerHTML, that is a in this case.
How do i get original innerHTML sample again onmouseout?
I want this to be done in javascript.
I tried another way more
function fun1()
{
document.getElementById("bd").innerHTML="a";
}
function fun3()
{
var ds=document.getElementById("bd").innerHTML;
alert(ds);
}
function fun2()
{
document.getElementById("bd").innerHTML=fun3();
}
but it is not working also.
A very generic version would be the following:
First change your markup a bit:
<h1 id="bd" onmouseover="fun1(this)" onmouseout="fun2(this)"> sample</h1>
This way you don't need to look up your element again in your callback function. This works then for more than one element you mouse over. Then you go:
function fun1(elm) {
if (!fun1.cache) fun1.cache = {}; // extend your function with a cache
fun1.cache[elm.id] = elm.innerHTML; // write into cache -> fun1.cache.bd
elm.innerHTML = 'a';
}
function fun2(elm) {
if (fun1.cache && fun1.cache[elm.id]) { // see if cache exists and...
elm.innerHTML = fun1.cache[elm.id]; // read from it
}
}
This way you build a caching system that doesn't need an extra global variable but stays closer to your function.
The next step would be to use only one function and send the new value as a parameter. Create something like a toggle function:
<h1 id="bd" onmouseover="fun(this, 'a')" onmouseout="fun(this)"> sample</h1>
and then your function:
function fun(elm, newValue) {
if (!fun.cache) fun.cache = {};
var value = newValue || fun.cache[elm.id]; // no newValue means recover old value
fun.cache[elm.id] = elm.innerHTML; // alway save the old value
elm.innerHTML = value;
}
If you need more explanations about this and creating Objects just leave a comment to this answer and I'll come back with more details...
Good luck!!
Store the first innerHtml in a global variable ,and use this variable to backup the first innerHtml.
var oldInner = '';
function fun1()
{
oldInner = document.getElementById("bd").innerHTML;
document.getElementById("bd").innerHTML="a";
}
function fun2()
{
document.getElementById("bd").innerHTML=oldInner;
}
You'll need to store the original value somehow:
var originalInnerHTML = "";
function fun1()
{
originalInnerHTML = document.getElementById("bd").innerHTML;
document.getElementById("bd").innerHTML="a";
}
function fun2()
{
document.getElementById("bd").innerHTML=originalInnerHTML
}
Currently you just get the existing innerHTML and set it as the new innerHTML - it's always going to be the same. So this line never changes anything:
document.getElementById("bd").innerHTML=document.getElementById("bd").innerHTML;
once you have changed the innerhtml of an element, old data is gone
In order to get the old data you first need to have it store in some other place.
For ex : on mouseover you can first copy the original html to a hidden div, and upon mouseout you can again copy from the hidden div to the main div.
hope this helps.
A very easy implementation will be to have the two text you want to display in the div. so you have:
<h1 id="bd">
<span id='sample1'>sample1</span>
<span id='sample2' style='display: none'>a</span>
</h1>
var el = document.getElementById("bd");
el.onmouseover = function() {
document.getElementById("sample1").setAttribute("style", "display: none");
document.getElementById("sample2").setAttribute("style", "");
}
el.onmouseout = function() {
document.getElementById("sample2").setAttribute("style", "display: none");
document.getElementById("sample1").setAttribute("style", "");
}
I am trying to write a PHP Java Script, but struggling to write in this section of coding.
I am trying to make a buttom in form in that opens
The code I have written so far is
function display(e){
if (e.clicked)
document.getElementById('2').style.display = 'none';
else
document.getElementById('2').style.display = 'block';
and the FORM CODE is;
<input type="button" value=" Book Now " onClick="display(this)"/></input>
any help to point out my clear mistakes would be great, the live code can be seen at
http://affordablecleaners.co.uk/quote/
Thanks,
Henry
Try something similar to the following
var i = 0;
var display = function() {
document.getElementById('2').style.display = (i++ % 2) ? "none" : "block";
};
Essentially, we're creating a variable i and increasing it by one every time the function is called. If, when the function is called, i is an even number, then we set it to display: block. Otherwise, set it to display: none.
The biggest downside to this solution is cluttering the global scope. If this is an issue, you can also do the following.
var display = function() {
document.getElementById('2').style.display = (document.getElementById('2').style.display == "none") ? "block" : "none";
};
Here's the (untested) logic...
function display(state, which){
if (state==1) {document.getElementById(which).style.display ='none';}
else
{document.getElementById(which).style.display = 'block';}
}
and then in your button...
to turn ON
onclick="display('1',someDIV)"
to turn OFF
onclick="display('0',someDIV)"