JS code to change parameter 'top' on click - javascript

Here is the pen I've created.
HTML
<div class = 'cc'>
<div class = 'bb'><div class = 'aa'> Some word </div></div>
</div>
CSS
.cc {
width: 100%;
min-height: 90px;
margin: 0;
padding: 0;
border: 1px solid #999999;
border-radius: 3px;
padding-left: 20px;
padding-right: 20px;
font-family: "Calibri";
font-size: 17px;
color: #666666;
background-color: rgba(0,0,0,.0);
}
.bb {
height: 100px;
width: 100%;
background-color: rgba(0,0,0,.5);
}
.aa {
position: relative;
top: 50%;
transform: translateY(-50%);
}
Now I want to create a clickable event such that when user click on class bb, page will check the top parameter of class aa - if it is 50% then smoothly change that to 10% and vice versa.
I want to use JavaScript code to achieve that. How can I do that?

hey just tried to gave shot at it , seems its working please look into this
let bb = document.querySelector('.bb');
let aa = document.querySelector('.aa');
bb.addEventListener('click',e => {
let top = window.getComputedStyle(aa).getPropertyValue('top');
if(top === '50px'){
aa.style.top = '10%';
}else{
aa.style.top = '50%';
}
})

Got it. It is tested and it seems to work.
let bb = document.querySelector('.bb');
let aa = document.querySelector('.aa');
bb.addEventListener('click', function(){
if(window.getComputedStyle(aa).getPropertyValue('top') === '50px'){
aa.style.top = '10%';
}else{
aa.style.top = '50%';
}
})
First, I used querySelector to get .bb and .aa.
Then, I added a event listener to bb.
Next, in the event listener I used window.getComputedStyle(), got the value of top from it and checked if it is 50px.
Last of all, if it is, change that to 10%, else change it to 50%.
I did this on CodePen, you can check it here (notice I changed the style from gray to white because gray is hard to read inside a black box).

Related

Automatic Resizing Function

So I have a bar that contains many smaller divs inside it, each with the same class.
.outer-bar{
width: 100%;
height: 50px;
background-color: blue;
}
.outer-bar button {
width: 50px;
height: 40px;
outline: none;
background-color: white;
border: none;
margin-top: 5px;
margin-bottom: 5px;
float: left;
margin-left: 2px;
}
<div class = "outer-bar">
<button class = "a">Hi</button>
<button class = "a">Hi</button>
<button class = "a">Hi</button>
<button class = "a">Hi</button>
<button class = "a">Hi</button>
<button class = "a">Hi</button>
<button class = "a">Hi</button>
<button class = "a">Hi</button>
<button class = "a">Hi</button>
</div>
When the window resized, I want the window to only show enough of them that there is no overflow, but there is as many as there can be.
So using: window.addEventListener("resize", function() {} );, is there any way to implement that?
One great example I saw was on Google Docs, where their bar automatically adjusts.
I would prefer doing this with Javascript and CSS and no Jquery or external libaries. (Note that I simplified the widths and number of elements for illustration purposes although the basic idea is still the same). I also prefer the use of for loops and document.getElementsByClassName("a").
I already started it by using:
var ribbon = document.getElementsByClassName("outer-bar")[0];
var prevChild = 0;
for(var i = 0; i < ribbon.children.length; i++) {
if(ribbon.children[i].getBoundingClientRect().right < prevChild) {
for(var c = i; c < ribbon.children.length; c++) {
ribbon.children[c].style.display = "none";
}
break;
}
prevChild = ribbon.children[i].getBoundingClientRect().right;
}
Although that method does not make the children displayable once I resize the window to be bigger.
If you know ribbon length why not divide it by the size you want the button to be. Then loop through the buttons making the first ones(ribbon length/size) block and the rest none.
I am not sure I understand you right, but it looks like you need to do a different styling to the inner divs when the screen resizes. CSS is capable of handling this for you without needing to use JavaScript at all.
Media Queries let you specify different styling based on the current size of the window.
.outer-bar button {
width: 50px;
height: 40px;
outline: none;
background-color: white;
border: none;
margin-top: 5px;
margin-bottom: 5px;
float: left;
margin-left: 2px;
}
#media screen and (max-width: 600px) {
.outer-bar button {
/*
Specify here any different styling
Ex.
*/
width: 25px;
}
}

How to change an ID depending on the color of an element with Javascript

I'm trying to learn javascript on my own, so I'm lacking a lot. I'm trying to change the color of multiples elements depending on the color in the css of another element.
I want the javascript to detect the <div id> with a specific color, and then change the id of another <div id2>
I tried this :
if (document.getElementById("name").css('color') == "#7a5cd4") {
document.getElementById('border').setAttribute('id', 'red');
document.getElementById('line').setAttribute('id', 'linered');
}
#name {
font-size: 35px;
color: #7a5cd4;
}
#border {
width: 25px;
height: 25px;
border: 3px solid black;
padding: 10px;
margin: 10px;
border-radius: 100%
}
#red {
width: 25px;
height: 25px;
border: 3px solid red;
padding: 10px;
margin: 10px;
border-radius: 100%
}
#line {
width: 200px;
height: 20px;
border: 1px solid black
}
#linered {
width: 200px;
height: 20px;
border: 1px solid red
}
<center>
<div id="name">name</div>
<div id="border"></div>
<div id="line"></div>
</center>
window.getComputedStyle is a function that takes an element as a parameter and returns an object containing all of the styles that are being used on that object. We can then call getPropertyValue on the result to get the value of a css property.
These functions return colours in the form rgb(r, g, b), so we will need to compare the value to rgb(122, 92, 212), instead of #7a5cd4.
HTMLElement.style, however, would not work in your case as it only gets the inline style, which is when you specify the style in your html, like <div style="color: red">.
Also, it is recommended to use classes for selecting elements, instead of ids, as you can place multiple of them on the same element.
const element = document.getElementById('name');
const styles = window.getComputedStyle(element);
if (styles.getPropertyValue('color') == 'rgb(122, 92, 212)') {
document.getElementById('border').setAttribute('id', 'red');
document.getElementById('line').setAttribute('id', 'linered');
}
In order to change the id of element you:
document.getElementById('oldid').id = 'newid'
This rest of this answer fit to inline style (element style="color: value") while #BenjaminDavies answer fit more to your original question:
In order to check/change color property you:
var divOldColor = document.getElementById('oldid').style.color; // get the color to variable
if (divOldColor == '#7a5cd4') { // do something }
Put it all together we get something like this:
if (document.getElementById('name').style.color == '#7a5cd4') {
document.getElementById('border').id = 'red';
document.getElementById('line').id = 'linered';
}
.css() is not a vanilla JS function. Use .style.cssPropertyName instead.
if (document.getElementById("name").style.color === "#7a5cd4") {
document.getElementById('border').setAttribute('id', 'red');
document.getElementById('line').setAttribute('id', 'linered');
}

Javascript only on scroll events?

Is it possible to create a minimalist javasript only on-scroll function to hide my menu bar, so only the menu button shows and the button itself gains a white backgroud colour? I have been looking into this and I believed to have the code fairly down. But I am very new to javasript and cannot fully understand the syntax of it yet. Below is what I have now in a jsfiddle:
https://jsfiddle.net/AngusBerry/zLt0yLou/2/#&togetherjs=Vsth32pa6L
html:
<!DOCTYPE html>
<body>
<header>
<h1><span id="tstscroll">0</span></h1>
<div class="MenuButton" id="mobMenu"></div>
<!--<p>as you can see, this is the header for the website. Here will also be contained all of the links to anywhere on the support system. this and the footer will both be FIXED and will move with the page.</p>-->
</header>
</body>
css:
header {
top: 0px;
position: fixed;
max-height: 100px;
width: 100%;
padding-top: 2px;
padding-bottom: 3.5px;
color: green;
animation: max-height-header;
animation-duration: 1.5s;
}
header h1 {
position: relative;
float: left;
margin-left: 3px;
}
header .MenuButton {
width: 28px;
height: 6px;
border-top: 6px solid;
border-bottom: 18px double;
margin-right: 5px;
margin-top: 2px;
}
javascript:
var mobilemenu = document.getElementById('mobMenu');
var testscroller = document.getElementById('tstscroll');
var x = 0;
document.mobilemenu.addEventListener("scroll", menuScrolMob);
function menuScrolMob(mobilemenu.onscroll) {
testscroller.innerhtml = x += 1;
}
You'll need to run that script either last in your body, or after page been loaded, or else it won't be able to access the elements.
Also, your script code is wrong, so here is a solution showing how to solve both those issues
(function(w, d) { /* this is a closure and will keep its variables
from polluting the global namespace and it also
declare 2 variables (w, d) to be used inside it */
w.addEventListener("load", function() {
var mobilemenu = d.getElementById('mobMenu');
var testscroller = d.getElementById('tstscroll');
var x = 0;
mobilemenu.addEventListener("scroll", function() {
testscroller.innerhtml = x += 1;
});
});
}(window, document)); /* here I pass the window and document object into the
closure's variables (w, d) to make the code slimmer */

How do I create an If Else condition based on margin styles

I'm having difficulty making this animation come to fruition upon a click with an If Else condition within it. So the #joinbox starts at "margin-top" of 7%, I want it to move on a click from #paper4 to a "margin-top" of -19%; only if it's already at 7% though. If not, I'd like it to move back to 7% upon the click. Also, I'm using the velocity js which is just a smoother .animate function.
$("#paper4").click(function() {
if ($("#joinbox").css("margin-top")=="7%")
{$("#joinbox").velocity({"margin-top": "-19%"}, 200, "easeInOutQuad");}
else {$("#joinbox").velocity({"margin-top": "7%"}, 200, "easeInOutQuad");}
});
Here is the original style of #joinbox
#joinbox {
margin-top: 7%;
margin-left: 31.5%;
width: 35%;
position: fixed;
box-shadow: 0 5px 10px #332E2C;
background-color: white;
padding: 1%;
}
According to my memory .css("margin-top") returns something in pxlike 7px not percent like 7% so maybe try converting the percentage to px. you could use something like $().offset for conversion.
Try doing console.log($("#joinbox").css("margin-top")) you wont get percentage I think.
Since you will only retrieve the value in px. You can use the parent width and calculate the % by hand.
Something like this:
$("#paper4").click(function() {
var elementMargin = parseInt($('#joinbox').css('margin-top')),
parentWidth = Math.round($('#joinbox').parent().width() * 0.07);
if(elementMargin === parentWidth) {
console.log('margin-top: 7%')
} else {
console.log('margin-top: -19%')
}
});
#joinbox {
margin-top: 7%;
margin-left: 31.5%;
width: 300px;
height: 100px;
background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="joinbox">
</div>
<button id="paper4">Hay</button>

Forcing mobile devices to activate :hover CSS properties on first touch and activate link on second touch

: )
So, I'm trying to solve a hover effect issue. I have tooltips on some of my links. Code looks like this:
<a href="https://wikipedia.org/wiki/Space_Shuttle_Atlantis">
<h6 class="has-tip">Space Shuttle
<p class="tip">The space shuttle was invented by Santa Claus</p>
</h6>
</a>
And the CSS is a bit more involved:
.tip {
display: block;
position: absolute;
bottom: 100%;
left: 0;
width: 100%;
pointer-events: none;
padding: 20px;
margin-bottom: 15px;
color: #fff;
opacity: 0;
background: rgba(255,255,255,.8);
color: coal;
font-family: 'Ubuntu Light';
font-size: 1em;
font-weight: normal;
text-align: left;
text-shadow: none;
border-radius: .2em;
transform: translateY(10px);
transition: all .25s ease-out;
box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
}
.tip::before {
content: " ";
display: block;
position: absolute;
bottom: -20px;
left: 0;
height: 20px;
width: 100%;
}
.tip::after { /* the lil triangle */
content: " ";
position: absolute;
bottom: -10px;
left: 50%;
height: 0;
width: 0;
margin-left: -13px;
border-left: solid transparent 10px;
border-right: solid transparent 10px;
border-top: solid rgba(255,255,255,.8) 10px;
}
.has-tip:hover .tip {
opacity 1;
pointer-events auto;
transform translateY(0px);
}
Now, on desktop this works wonderfully. You hover over the tiny title and you get a pretty looking tooltip, then if you click anywhere on the title or tooltip (unless you decide to put yet another link in the paragraph which works separately and nicely) you activate the link. Yay : )
Now on mobile, the whole thing gets funky. Touching just activates the link. If you have slow internet, or iOS, you might glimpse the tooltip just as the next page loads.
I would like the following behavior:
User taps on tiny title (h6) which has class (has-tip)
If this is the first tap, the tooltip shows, and nothing else happens. 3)
If the tooltip is already showing when they tap (as in a subsequent
tap) then the link is activate and the new page loads.
Any ideas how I might implement this? No jQuery if possible.
One way to do it is to save a reference to the last clicked has-tip link and to apply a class to it which forces the tip to show. When you click on a link and it matches the the last one clicked, you let the event pass.
EDIT: oh, I forgot to mention you might need a classList shim for old IE.
JSFiddle link.
HTML
<a href="http://jsfiddle.net/1tc52muq/5/" class="has-tip">
JSFiddle<span class="tip">Click for some fun recursion</span>
</a><br />
<a href="http://google.com" class="has-tip">
Google<span class="tip">Click to look for answers</span>
</a>
JS
lastTip = null;
if(mobile) {
var withtip = document.querySelectorAll(".has-tip");
for(var i=0; i<withtip.length; ++i) {
withtip[i].addEventListener("click", function(e) {
if(lastTip != e.target) {
e.preventDefault();
if(lastTip) lastTip.classList.remove("force-tip");
lastTip = e.target;
lastTip.classList.add("force-tip");
}
});
}
}
CSS
.has-tip {
position: abolute;
}
.tip {
display: none;
position: relative;
left: 20px;
background: black;
color: white;
}
.has-tip:hover .tip, .force-tip .tip {
display: inline-block;
}
Edit: Just wanted to say that Jacques' approach is similar, but much more elegant.
On touch devices, you'll need to make a click/tap counter:
1) On first tap of any link, store the link and display the hover state.
2) On another tap, check to see if it's the same as the first, and then perform the normal tap action if it is. Otherwise, clear any existing hovers, and set the new tap target as the one to count.
3) Reset / clear any hovers if you tap on non-links.
I've made a rudimentary JSFiddle that console.logs these actions. Since we're not using jQuery, I didn't bother with adding/removing CSS classes on the elements.
Also, sorry about not writing taps instead of clicks.
var clickTarget;
var touchDevice = true;
if(touchDevice) {
var links = document.getElementsByTagName('a');
for(var i=0; i<links.length; i++) {
links[i].onclick = function(event) {
event.stopPropagation();
event.preventDefault(); // this is key to ignore the first tap
checkClick(event);
};
};
document.onclick = function() {
clearClicks();
};
}
var checkClick = function(event) {
if(clickTarget === event.target) {
// since we're prevent default, we need to manually trigger an action here.
console.log("Show click state and also perform normal click action.");
clearClicks();
} else {
console.log("New link clicked / Show hover");
clickTarget = event.target;
}
}
var clearClicks = function() {
console.log("Clearing clicks");
clickTarget = undefined;
};
http://jsfiddle.net/doydLt6v/1/

Categories

Resources