Writing a boolean expression to solve - javascript

While working through the application process for a bootcamp, I was tasked with the following JS problem which is above my head. I was successful in testing through the JS console on Chrome but when I attempt to plug the code into the .js file, it does not work. Do I need to apply a boolean expression? If so, what is the best way of coding it?
Here is everything that is in the .js file:
document.addEventListener("DOMContentLoaded", function(event) {
var thumbnailElement = document.getElementById("smart_thumbnail");
thumbnailElement.addEventListener("click", function() {
// write here
});
});
Here is the problem that is at hand:
"To make the image bigger or smaller, you have to change its class. In your JavaScript console, run this code:
var thumbnailElement = document.getElementById("smart_thumbnail");
thumbnailElement.className; This displays what the class currently is; it
should be
"small", unless you changed it since.'
To make it big, you should remove the class, by running this:
thumbnailElement.className = ""; To make it small again, you can put it back:
thumbnailElement.className = "small";'
See how it changes from small to big? You should put the line that makes it big in your JavaScript file so that it executes when the user clicks."

You could use the HTMLElement.classList.toggle method to add or remove the class. Here is a small snippet that illustrates how you can do it.
<style>
.small {
transform: scale(0.5);
}
</style>
<button class="small" id="smart_thumbnail">Click me</button>
<script>
document.addEventListener("DOMContentLoaded", function (event) {
// Get the element by id
var thumbnailElement = document.getElementById("smart_thumbnail");
// add the event listener on the element
thumbnailElement.addEventListener("click", function () {
thumbnailElement.classList.toggle("small");
/*
HTMLElement.classList.toggle(className) will remove the class if it is in the class list OR add it if it is not already there.
*/
});
});
</script>
If you simply want to remove it, you can use the remove method instead.
thumbnailElement.classList.remove("small");

if you have the css of the elment in the id and changing its size by class then it will not work here is the code that I wrote to solve
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Answer</title>
<style>
.small{
width: 10%;
height: 10%;
transition: all 1s ease;
}
.notSmall{
width: 30%;
height: 30%;
transition: all 1s ease;
}
</style>
</head>
<body>
<img src="Your Image" class="small" id="smart_thumbnail" alt="The image">
<script>
document.addEventListener("DOMContentLoaded", () => {
let thumbnailElement = document.getElementById("smart_thumbnail");
thumbnailElement.addEventListener("click", function() {
if(thumbnailElement.classList == "small"){
thumbnailElement.classList.remove('small');
thumbnailElement.classList.add('notSmall');
console.log('now image is big')
}else{
thumbnailElement.classList.add('small');
thumbnailElement.classList.remove('notSmall');
console.log('now image is small')
}
});
});
</script>
</body>
</html>

Related

How can I get rid of onclick in my js code, any alternative?

How can I execute the following js function inside js instead of using a button with it? Also, can it be achieved without jQuery?
The function is myFunction()
The button is:
<button onclick="myFunction()">Toggle dark mode</button>
The full code is:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
padding: 25px;
background-color: white;
color: black;
font-size: 25px;
}
.dark-mode {
background-color: black;
color: white;
}
</style>
</head>
<body>
<h2>Toggle Dark/Light Mode</h2>
<p>Click the button to toggle between dark and light mode for this page.</p>
<button onclick="myFunction()">Toggle dark mode</button>
<script>
function myFunction() {
var element = document.body;
element.classList.toggle("dark-mode");
}
</script>
</body>
</html>
Also, instead of using a button, use a span with a css pointer settle.
So basically I'm trying to achieve something like this:
HTML:
<span id="mybutton">Toggle nightmode</span>
JS:
<script>
function myFunction.getElementbyID(#mybutton).(click) {
var element = document.body;
element.classList.toggle("dark-mode");
}
</script>
It's ok if you offer a solution in jQuery, but I prefer vanilla javascript.
There are quite a few ways to achieve this, the shortest way would just be to do:
document.getElementById('mybutton').onclick = () => { /* CODE GOES HERE */ };
If your function is already defined somewhere, you can replace the lambda function (This ()=>{} thingy) with the name of your function, leaving you with this:
document.getElementById('mybutton').onclick = myFunction;
However, all that does is set the onlcick property of your element programatically, rather than setting it inline. If you want your element to not have the onclick property at all, you need to set an event listener for that element. This can be done like so:
document.getElementById('mybutton').addEventListener('click', () => {
/* CODE GOES HERE */
});
Once again, that lambda function can be swapped out for the name of your function if its already defined somewhere else.
tldr your script element should look like:
<script>
document.getElementById('mybutton').addEventListener('click', () => {
var element = document.body;
element.classList.toggle("dark-mode");
});
</script>

How can I call a CSS animation on a nested element within a parent element?

I'm looking to remove a class from a nested div element upon focus of the parent. Then I want to replace the class with another that has a CSS animation that will autoplay. I'm looking to do this within multiple elements in the same class as well so it will need to be able to handle more than one. I'm not sure what to do as I've kind of reached to where I believe I should be at this point but to no avail.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<style>
<style>
div {
filter: opacity(0%);
background-color: red;
width: 300px;
height: 300px;
position: relative;
top: 50%;
left: 50%;
z-index: 1;
}
.noGrow {
}
.grow {
animation-name: derp;
animation-duration: 1s;
filter: opacity(100%);
}
#keyframes derp {
from{width: 0px;}
to{width: 300px;}
}
</style>
<body>
<span id="divHolder" tabindex="1">
<div class="noGrow firstDiv">
</div>
</span>
</body>
<script src="jquery.js"> </script>
<script>
var divHolder = $(".divHolder");
var firstDiv = $(".firsDiv");
divHolder.focus(function () {
if($(".firstDiv").hasClass("noGrow")){
$(this).removeClass("noGrow");
$(this).addClass("grow");
console.log("It's working.");
}
});
</script>
</html>
Thank you for any and all help. It is much appreciated.
Looking at your code, these two lines seem to be the problem:
$(this).removeClass("noGrow");
$(this).addClass("grow");
$(this) refers to the divHolder element you are binding the focus event to. If you want to change the class of firstDiv, you'll need to change the lines to this:
firstDiv.removeClass('noGrow');
firstDiv.addClass('grow');
However, based on your CSS, I would suggest using toggleClass, and leaving the noGrow class off completely. Your div becomes:
<div class="firstDiv"></div>
and your JS becomes:
divHolder.focus(function () {
firstDiv.toggleClass('grow');
console.log('growing!');
});
Finally, if you don't know where in the list of descendants your 'growable' div will be, you can use something like find():
divHolder.focus(function(){
$(this).find('div').toggleClass('grow');
// if the div is given an id like #growable we can do this:
// $(this).find('#growable').toggleClass('grow');
});

Click Element isn't showing/hiding properly

I have an issue with my code, I'm trying to create a function to hide and show a div
and it's working, but it dosnt work at first, It works only on the second click, so i have to click the link first to get it to start working properly, how can i fix it so that it works on first click?
more info:
im trying to have a div appear and then disapear usin the display and hide functions, the catch is i also want it to disapper when im outside of the div, if its visible, its all working but the problem is when i first load the page thn click the link to display the div, it dosnt appear, only when i click it a second time does it appear. this is the problem i want to fix
this is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/jquery.foggy.min.js"></script>
<style>
body {
background: black;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: 100%;
color: white;
font-family: 'Segoe UI';
font-size: 24px;
}
.box
{
width: 100%;
margin: auto;
top: 0px;
left: 20%;
right: 0px;
bottom: 0px;
background-color: white;
opacity: 0.4;
position: fixed;
overflow-y: scroll;
overflow-x: scroll;
}
</style>
</head>
<body>
<script lang="en" type="text/javascript">
$(document).ready(function () {
});
$(document).mouseup(function (e) {
var container = $("#boxwrapper");
if (!container.is(e.target) && container.has(e.target).length === 0) {
if (container.is(':visible'))
Hide();
}
});
function Display() {
$("#boxwrapper").show();
$("#boxwrapper").addClass("box");
$("#main").foggy();
}
function Hide() {
$("#boxwrapper").hide();
$("#main").foggy(false);
}
</script>
<div id="main">
Display Div
</div>
<div id="boxwrapper">
</div>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</body>
</html>
Why don't you use click() method insead of mouseup()?
$('a').click(function (e) {
var container = $("#boxwrapper");
if (container.is(':visible')) {
Hide();
} else {
Display();
}
return false;
});
If you don't want to bind this event to every <a> on your site, add class to your element and bind click to this class. E.g.:
Display Div
and then in your script:
$('a.divToggle').click(function (e) { });
See this working fiddle
JavaScript
function display() {
if ($('#boxwrapper ').css('display') === 'none') {
$('#boxwrapper').show();
} else {
$('#boxwrapper').hide();
}
}
The issue could be a whitespace or anything, since is very hard to reproduce it, but here some advices or things that could be causing the issue:
Organize your code
First of all, you need to organize your code and load the JS libraries at the end of the file or wrap your functions inside the $(document).ready.
If you are using jQuery already, why to use the onClick event on the element itself if you can do it with jQuery.
Instead of all code inside the document mouseUp event, you could just add display: none in the css to #boxwrapper.
Instead of Hide() and Show() functions, you could just use toogleClass('box') jquery function
Difference between Click and MouseUp events
With a mouseup event, you can click somewhere else on the screen, hold down the click button, and move the pointer to your mouseup element, and then release the mouse pointer. A click event requires the mousedown and mouseup event to happen on that element.
Prevent Default Maybe?
You are not preventing Default on your click event. You can do it like:
Display Div

How do I make <a> tags with a class unclickable?

I have some parent nav items with children and I don't need the parent items to be clickable.
They look like this:
Parent Item
Is there anyway to target the <a> tags with the specific class of .parent and make them unclickable?
If anyone interested in Pure CSS solution (As this question is tagged as CSS) than you can use pointer-events: none;
a[href="parent"] {
cursor: default;
pointer-events: none;
}
Demo
As far as support goes
Credits: Mozilla Developer Network
Use:
$(function () {
$('a.parent').on("click", function (e) {
e.preventDefault();
});
});
If you want to avoid using the jQuery library, it's just as easy without it:
var disabled = document.querySelector('.parent');
disabled.addEventListener('click', function(e) {e.preventDefault();}, false);
Another pure CSS option would be to overlay the link with an absolutely positioned "cover":
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
.parent {position: relative; z-index: -1;}
.parent:after {content: ""; position: absolute; top:0; right: 0; bottom: 0; left: 0;}
</style>
</head>
<body>
Disabled Link
Normal Link
</body>
</html>
Instead of a listener on every .parent, you can put a single listener on the body. The following will work in every browser in use without any library support:
function stopClickOnParentClass(evt) {
var el = evt.target || evt.srcElement;
if (/(^|\s)parent(\s|$)/.test(el.className)) {
evt.preventDefault();
return false;
}
}
then:
<body onclick="stopClickOnParent(event);" …>
You could also make the class dynamic by passing it to the function and building the regular expression from it.

Issue with jQuery : Click event & Switching between "active" elements

OK, here's my issue and I bet it'll be super-easy for you (I guess it wasn't... lol).
So, let's say I'm having several divs. Once the user clicks on one of them, I want to highlight just this one. In a few words : a) remove (if exists) a specific class from all divs, b) add it to the div being clicked.
And here's the full code...
index.html
<!DOCTYPE html>
<html style='min-height:0px;'>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1">
<link rel="stylesheet" href="jquery.mobile.min.css" />
<link rel="stylesheet" href="custom.css" />
<script src="jquery.min.js"></script>
<script src="jquery.mobile.min.js"></script>
</head>
<body>
<div data-role="page">
</div>
<script src="custom.js"></script>
</body>
</html>
custom.js
$(function() {
$("div").click( function() {
$("div").removeClass("msp-selected");
$(this).addClass("msp-selected");
});
});
custom.css
media screen and (orientation: portrait) {
.ui-mobile, .ui-mobile .ui-page {
min-height: 420px;
}
}
media screen and (orientation: landscape) {
.ui-mobile, .ui-mobile .ui-page {
min-height: 300px;
}
}
div {
outline:0;
}
div:hover {
outline-width:1px;
outline-color:red;
outline-style: dotted;
overflow:hidden;
}
.msp-selected {
outline-width:1px;
outline-color:red;
outline-style: solid;
}
P.S.
The situation may not be as simple as it initially seemed. I'm using jQuery 1.8.2 and jQuery Mobile 1.3.2. And the actual page is running inside a Webview, itself inside a Cocoa/OS X app. Quite complicated, huh? lol
I can't see any error (not easy to have access to a console that... doesn't exist...). The only thing that I noticed is that when I remove the removeClass part, it does work. Adding it, seems to make the whole thing a mess.
$(function() {
$('div').on( "click", function() {
$(this).addClass('msp-selected');
$(this).siblings().removeClass('msp-selected');
})
Try something like:
$(".box").click( function() {
if($(".activeBox").length > 0) { //check if there is an activeBox element
$(".activeBox").removeClass("activeBox"); //if there is, remove it
}
$(this).addClass("activeBox"); //make the clicked div the activeBox
});
.box and .activeBox classes to be replaced by your own inactive and active selectors as you want.
Here's a jsFiddle example
Update:
With the new HTML, I got this working as a jsFiddle
Here's the code:
HTML within jsFiddle's existing head/body tags:
<div data-role="page">
</div>
CSS from OP:
div {
outline:0;
}
div:hover {
outline-width:1px;
outline-color:red;
outline-style: dotted;
overflow:hidden;
}
.msp-selected {
outline-width:1px;
outline-color:red;
outline-style: solid;
}
jQuery:
$("div").click( function() {
if($(".msp-selected").length > 0) {
$(".msp-selected").removeClass("msp-selected");
}
$(this).addClass("msp-selected");
});
I tested this with the various versions of jQuery available back to 1.7.2 and mobile 1.1.1, with the class being added on click each time. My only suggestion if this still doesn't work is to encase the whole thing in $(document).ready( function() { //click function }); or switch to $("div").on("click", function() {});

Categories

Resources