How can I control CSS with a button in JS - javascript

I Can not find the right code for the JS to control CSS. Upon opening link I need the "transform" to be off , and then turn on and toggle back and forth "transform" with the button. It started as an on/off mute button needing no css , so my paths ?
The buttons ( play/pause/etc)are in a div . Their function are in JS and all work, except, I need this one to reach into CSS but can't find my brain. A delete of the CSS and it opens and runs everything else and runs the way I would like. Thanks.
<button onclick="transform()">mirror</button>
#myplayer {
transform: rotateY(180deg);
}
var player = document.getElementById("myplayer");
function transform() {
if (player.transform)
player.transform = false
else
player.transform = true
}

Get the button element, add a click event handler to it, within the handler once the button is clicked, grab the video element then use .classList.toggle('class-name') to toggle a class.
document.getElementById("transformPlayer").addEventListener("click", function() {
document.getElementById("player").classList.toggle('transform180')
});
.transform180 {
transform: rotateY(180deg);
}
<button id="transformPlayer">mirror</button>
<video id="player" controls width="250">
<source src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm"
type="video/webm">
<source src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4"
type="video/mp4">
</video>

change this
function transform() {
if (player.transform)
player.transform = false
else
player.transform = true
}
To this
function transform() {
if (player.style.transform){
player.style.transform = "";
}
else{
player.style.transform="rotate(180deg)";
}
}

Use a class
const player = document.querySelector('#myplayer')
const button = document.querySelector('button')
button.addEventListener('click', () => {
player.classList.toggle('rotate')
})
#myplayer {
background: red;
height: 100px;
width: 100px;
color: white;
}
#myplayer.rotate {
transform: rotateY(180deg);
}
<button>mirror</button>
<div id="myplayer">:)</div>

Related

Two animations using css, javascript, two buttons onclick()

I want to create two animations in css. In my project, I use two button, one object. I care, that the first button is being clicked, the first animation on the object is being run.
I know, what I should do, when I have one button and one animation, but I do not know how to solve problem with two different animations on the same object.
Edit 3. I find problem!
Does this meet your requirements?
let btn_a = document.getElementById('a')
let btn_b = document.getElementById('b')
let btn_c = document.getElementById('c')
let div = document.getElementById('obj')
btn_a.addEventListener('click', function() {
div.className = 'anim-a'
})
btn_b.addEventListener('click', function() {
div.className = 'anim-b'
})
btn_c.addEventListener('click', function() {
$('#obj').animate({}, function(){
$('#obj').css({transform: 'rotate(30deg) translate(200px)'})
})
})
div {
background-color: pink;
width: 100px;
transition: all linear 0.5s;
}
.anim-a {
background-color: yellowgreen;
width: 150px;
}
.anim-b {
background-color: grey;
width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='obj'>animated</div>
<button id='a'>anim-a</button>
<button id='b'>anim-b</button>
<button id='c'>anim-c</button>
EDIT
Without css fields, assuming that you're using jQuery, you can use .animate(). However, .animate() won't take transform as its property. We'll do this in the callback.
btn_c.addEventListener('click',function() {
$('#obj').animate({}, function(){
$('#obj').css({transform: 'rotate(30deg)'})
})
})

If statement to check css property not working

I have a div that displays a little popup menu when clicked. I want users to be able to click anywhere in the body of the site to close the popup, but when I add code for that, the popup cant be opened at all anymore.
So I tried adding an if-statement so that the closemenu() function will only try close the popup if its already open, but it seems like the statement is evaluating to false even if the popup is open.
Here is the HTML for showing the popup:
<div class="popcolor" onclick="showmenu()"> Click!
<span class="popupcolor" id="myPopup">Pop!</span>
</div>
Here is the css:
.popcolor .show {
visibility: visible;
-webkit-animation: fadeIn 0.5s;
animation: fadeIn 0.5s;
}
Here is the Javascript:
function showmenu() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}
function closemenu() {
var popup = document.getElementById("myPopup");
if (popup.style.visibility == "visible") {
popup.classList.toggle("close");
};
}
Here is the HTML for closing the popup:
<body onclick="closemenu()">
I've been through every post I can find on this for solutions, and I'm still stuck. Any help is appreciated.
You can use the getComputedStyle() method on the window object, to calculate the style rules that result from the classes applied to your popup element.
This gives you a reliable way of determining the values of different styling rules that result from, say, the 'close' class being applied to popup
Something along the lines of this should work for you:
function closemenu() {
var popup = document.getElementById("myPopup");
// Get the computed style, that is the combination of styles
// resulting from your CSS classlist, etc
var computedStyle = window.getComputedStyle(popup, null);
// Get visibility value from computed styles
var visiblityValue = computedStyle.getPropertyValue("visibility")
if (visiblityValue == "visible") {
popup.classList.toggle("show"); // Correct this from "close" to "show"
};
}
There are also some other functional issues with your implementation which are causing problems. Consider updating your showmenu() method to:
function showmenu(event) {
// Prevent event propagation, which would cause closemenu to call
// after this method is called
event.stopPropagation()
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}
For more information on getComputedStyle(), see the MDN documentation
Problem here is that click event triggered from div bubbles up to body which eventually closes the popup.
function showmenu(e) {
e.stopPropagation();
console.log('toggle');
document.getElementById("myPopup").classList.toggle("close");
}
function closemenu(e) {
e.stopPropagation();
console.log('hide');
document.getElementById("myPopup").classList.add("close");
}
#myPopup.close {
visibility: hidden;
}
body {
border: 1px solid #ccc;
padding: 2rem;
}
<body onclick="closemenu(event)">
<div class="popcolor" onclick="showmenu(event)"> Click!
<span class="popupcolor close" id="myPopup">Pop!</span>
</div>
</body>
P.S. Use event.stopPropagation() to cancel/consume event
Because the visibility property is being set at the class level, the style information isn't available in the style property of your element. Maybe instead of checking for a specific style, you can check to see if the 'show' class is currently assigned to your element like so:
function closemenu() {
var popup = document.getElementById("myPopup");
if (popup.classList.contains("show")) {
popup.classList.toggle("close");
};
}
Problem in your code is with the use of JavaScript functions.
Try this simple example I took from W3Schools and enhanced it for your case.
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_add_class
There seems to be some issue with W3CSchool TryIt Editor page. Here is the link to JSBin for the same code: https://jsbin.com/xefolinape/edit?html,output
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.mystyle {
width: 100%;
padding: 25px;
background-color: coral;
color: white;
font-size: 25px;
box-sizing: border-box;
}
</style>
</head>
<body>
<p>Click the "Try it" button to add the "mystyle" class to the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<button onclick="myFunctionClose()">Close it</button>
<script>
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.add("mystyle");
}
function myFunctionClose() {
var element = document.getElementById("myDIV");
element.classList.remove("mystyle");
}
</script>
</body>
</html>
Hope this helps!

Disable video that is autoplaying at lower widths for mobile phones

I want my HTML5 video to disappear at 600px, as mobile phones don't autoplay and can't seem to run the javascript very well etc. The issue is my #media query to display none at 600px only non-displays the visual part of the video, not the audio - But I need the audio disabled as well below 600px. I have been researching this already on stack overflow and there are some possible solutions already, but I need help relating the code to my program if possible please.
There is a complication as I already have javascript running on my 'video' and "videoEnd" tags which is working fine and makes the video, padding and text disappear once the video is auto played.
Here is my existing code:
<html>
<video id="video" width="" height="" controls autoplay >
<source src="clip.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<div id="videoEnd" style="display:block">James Presents</div>
</html>
<script>
document.getElementById('video').addEventListener('ended',myHandler,false);
function myHandler(e) {
if(!e) { e = window.event; }
// What you want to do after the event
document.getElementById('video').style.display="none";
document.getElementById('videoEnd').style.display="none";
}
</script>
A previous answer is suggesting use this code to disable the video completely at a certain width, but being a novice I am not sure if the code is jquery or javascript and how to relate the code below to my id tags?
$(function() {
// onload
if(document.body.clientWidth >= 870) {
$('video').attr('autoplay', true);
}
// If you want to autoplay when the window is resized wider than 780px
// after load, you can add this:
$(window).resize(function() {
if(document.body.clientWidth >= 870) {
$('video').attr('autoplay', true);
}
});
});
UPDATED CODE BELOW
<script type="text/javascript">
$(function() {
var video = document.getElementById('video');
if (document.body.clientWidth >= 630) {
video.setAttribute('autoplay', true);
video.classList.remove('hide');
}
$(window).resize(function() {
if (document.body.clientWidth >= 630) {
video.classList.remove('hide')
video.play();
video.setAttribute('autoplay', true);
} else {
video.classList.add('hide');
video.removeAttribute('autoplay');
video.pause();
}
});
});
</script>
<video id="video" width="" height="" controls class="hide" >
<source src="clip.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<div id="videoEnd" style="display:block">James Presents</div>
<script>
document.getElementById('video').addEventListener('ended',myHandler,false);
function myHandler(e) {
if(!e) { e = window.event; }
// What you want to do after the event
document.getElementById('video').style.display="none";
document.getElementById('videoEnd').style.display="none";
}
</script>
//ALL CSS THAT RELATES IS BELOW
.hide {
display: none;
}
#videoEnd
{
margin-top:0;
margin-bottom:0;
text-align:center;
position:fixed;
z-index:9999;
top: 15%;
left: 50%;
/* bring your own prefixes */
transform: translate(-50%, -50%);
font-size:325%;
color:white;
font-family: Kroftsmann;
src:url('Kroftsmann.ttf');
}
video {
margin-top:10%;
width:65%;
position: fixed;
top: 40%;
left: 50%;
/* bring your own prefixes */
transform: translate(-50%, -50%);
background-color:rgb(15, 15, 15);
padding:2000px;
z-index:9999;
}
#media screen and (max-width:630px){
#videoEnd
{
visibility:hidden;
}
}
#media screen and (max-width:630px){
video
{
display: none;
visibility:hidden;
}
}
Remove the autoplay from your HTML video element to disable that as the default action, add the class .hide (or whatever you use to hide the element) so it's hidden by default. Then on load, add autoplay and remove .hide if the viewport width > your breakpoint.
Then on resize, if the viewport is < your breakpoint, add a CSS element that will hide the video (display: none;), remove the autoplay attribute if it exists, and pause() the video. If the viewport is > your breakpoint, undo all of that.
$(function() {
var video = document.getElementById('video');
if (document.body.clientWidth >= 870) {
video.setAttribute('autoplay', true);
video.classList.remove('hide');
}
$(window).resize(function() {
if (document.body.clientWidth >= 870) {
video.classList.remove('hide')
video.play();
video.setAttribute('autoplay', true);
} else {
video.classList.add('hide');
video.removeAttribute('autoplay');
video.pause();
}
});
});
.hide {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<p>something before the video</p>
<video id="video" controls class="hide">
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
<source src="https://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
<p>something after the video</p>
The code suggestion is a mix of jQuery and plain javascript.
Here is one way, using plain javascript, that will, on page load, check if width is wider than 600, and if so, show and play the video. Your existing event handler will hide it when done.
window.addEventListener('load', function() {
if (window.innerWidth >= 600) {
var vid = document.getElementById('video');
var wrap = document.getElementById('videowrapper');
wrap.classList.toggle('hide');
vid.play();
vid.addEventListener('ended',function(e) {
wrap.classList.toggle('hide');
});
}
})
.hide {
display: none;
}
<div id="videowrapper" class="hide">
<video id="video" controls>
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
<source src="https://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
<div>James Presents</div>
</div>

Swap background on hover

I'm trying to swap background using jQuery. But the problem is that it doesn't successfully switch to new background, instead, the old one is removed and I get a white background instead.
I've been googling and trying out putting the path as a var instead for example, and some other unsuccessful suggestions.
My jQuery function looks like the following:
$("#btn").hover(function () {
$('#page1').css('background-image','url(../images/bg1_normal.jpg)');
});
And my CSS for the default background looks like this:
#page1 {
height: 100vh;
max-height: 100vh;
background-image: url("../images/bg1_rw.jpg");
background-repeat: no-repeat;
background-size: 100%;
}
I'm using Java Play Framework and the pictures are in the same folder, and it is the correct path to it since the default background works.
EDIT: I Tried as well to use an img source from the web, just to be 100% sure it wasn't some issues with the path, but it still only makes it white.
I believe jQuery's hover() function isn't able to remove that particular style when the mouse leaves.
You could just do it yourself
$("#btn").on({
mouseenter : function() {
$('#page1').css('background-image','url(../images/bg1_normal.jpg)');
},
mouseleave : function() {
$('#page1').removeAttr('style');
// or simply set the backround again to the other image
}
});
Try .addClass and .removeClass functions - it's simple and all style work is done in stylesheet file:
$("#btn").on({
mouseenter : function() {
$('#page1').addClass('inverted');
},
mouseleave : function() {
$('#page1').removeClass('inverted');
}
});
and then simply add
#page1.inverted {
//style as you need
}
to your stylesheet.
If you're using images you could do an image swap like this
https://jsfiddle.net/RachGal/oee3guxz/
$("#flowers").mouseover(function () {
var _this = $(this);
var current = _this.attr("src");
var swap = _this.attr("data-swap");
_this.attr('src', swap).attr("data-swap", current);
_this.toggleClass("opaque");
});
.opaque {
opacity:.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<img id='flowers' class="full" src='http://www.rachelgallen.com/images/snowdrops.jpg' width="500" height="400" data-swap='http://www.rachelgallen.com/images/daisies.jpg' width="500" height="400" />
or if you could just use color like this
$("#color").mouseleave(function () {
$("body").css("background-color","black");
});
$("#color").mouseover(function (){
$("body").css("background-color","red");
});
$("#color").click(function(){
$("body").css("background-color","green");
});
body, #color {
height: 800px;
width: 800px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="color"> </div>
https://jsfiddle.net/RachGal/8p783jfo/
Hope this helps
Rach

Toggle visibility property of div

I have an HTML 5 video in a div. I then have a custom play button - that works fine.
And I have the video's visibility set to hidden on load and visible when the play button is clicked, how do I return it to hidden when the play button is clicked again?
function showVid() {
document.getElementById('video-over').style.visibility = 'visible';
}
#video-over {
visibility: hidden;
background-color: rgba(0, 0, 0, .7)
}
<div id="video-over">
<video class="home-banner" id="video" controls="">
<source src="http://video-js.zencoder.com/oceans-clip.mp4" type='video/mp4' />
<source src="http://video-js.zencoder.com/oceans-clip.webm" type='video/webm' />
<source src="http://video-js.zencoder.com/oceans-clip.ogv" type='video/ogg' />
</video>
</div>
<button type="button" id="play-pause" onclick="showVid();">
<img class="img-home-apply" src="/wp-content/images/apply-pic.png" alt="Apply Now">
</button>
I'm basically just trying to toggle it between the two states of visible and hidden except I can't use toggle because that show's and hides the div. I need it there, just hidden, so it maintains the correct height.
Using jQuery:
$('#play-pause').click(function(){
if ( $('#video-over').css('visibility') == 'hidden' )
$('#video-over').css('visibility','visible');
else
$('#video-over').css('visibility','hidden');
});
According to the jQuery docs, calling toggle() without parameters will toggle visibility.
$('#play-pause').click(function(){
$('#video-over').toggle();
});
http://jsfiddle.net/Q47ya/
There is another way of doing this with just JavaScript. All you have to do is toggle the visibility based on the current state of the DIV's visibility in CSS.
Example:
function toggleVideo() {
var e = document.getElementById('video-over');
if(e.style.visibility == 'visible') {
e.style.visibility = 'hidden';
} else if(e.style.visibility == 'hidden') {
e.style.visibility = 'visible';
}
}
To clean this up a little bit and maintain a single line of code (like you would with a toggle()), you can use a ternary operator so your code winds up looking like this (also using jQuery):
$('#video-over').css('visibility', $('#video-over').css('visibility') == 'hidden' ? 'visible' : 'hidden');
To do it with an effect like with $.fadeIn() and $.fadeOut() you can use transitions
.visible {
visibility: visible;
opacity: 1;
transition: opacity 1s linear;
}
.hidden {
visibility: hidden;
opacity: 0;
transition: visibility 0s 1s, opacity 1s linear;
}
It's better if you check visibility like this:
if($('#video-over').is(':visible'))
$.fn.toggleVisibility = function (state) {
return this.each(function () {
$(this).css("visibility", state ? "visible" :
(state === false ? "hidden" :
$(this).css("visibility") === "hidden" ? "visible" : "hidden"));
});
};
Then
$('#video-over').toggleVisibility();
or
$('#video-over').toggleVisibility(true);
or
$('#video-over').toggleVisibility(false);

Categories