How to use Javascript if statement when linked with bootstrap dropdown menu - javascript

I've hit a wall with trying to get my JavaScript if statement to work when using bootstraps drop down menu.
Goal: There are 2 drop down menu's. The user will select one value from each, based on what the user selects something will happen. I've seen many examples using the method however bootstrap seems to be a bit different. Also, I've seen a lot of people recommend jQuery because it's easier but I prefer to use Javascript (I'm learning). If someone can point me in the right direction I would appreciate it, or if my approach is totally off base please kindly let me know the right approach. Also, I currently don't have the "id" in my html because I'm not sure where to put it. Cheers.
HTML:
<!--Drop down Item 1 -->
<h3 class="display-4" style="font-size: 1.5rem;">What is your eye color</h3>
<div class="dropdown">
<button class="btn btn-info btn-sm dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="background-color: #588c7e;">
Eye Color
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#"><img src="img/brown_eye.jpg" class="rounded-circle" value="brown"> Brown</a>
<a class="dropdown-item" href="#"><img src="img/blue_eye.jpg" class="rounded-circle" value="blue"> Blue</a>
<a class="dropdown-item" href="#"><img src="img/green_eye.jpg" class="rounded-circle" value="green"> Green</a>
<a class="dropdown-item" href="#"><img src="img/hazel_eye.jpg" class="rounded-circle" value="hazel"> Hazel</a>
</div>
</div>
<!--Drop down Item 2-->
<h4 class="display-4" style="font-size: 1.5rem;"> What is your skin tone</h4>
<div class="dropdown">
<button class="btn btn-info btn-sm dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="background-color: #588c7e;">
Skin Tone
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton" onchange="dropdownChange();">
<a class="dropdown-item" href="#"><img src="img/fair.jpg" class="rounded-circle" value="fair"> Fair (porcelain)</a>
<a class="dropdown-item" href="#"><img src="img/light.jpg" class="rounded-circle" value="light"> Light (fair to light)</a>
<a class="dropdown-item" href="#"><img src="img/medium.jpg" class="rounded-circle" value="medium"> Medium (light to medium)</a>
<a class="dropdown-item" href="#"><img src="img/bronze_dark.jpg" class="rounded-circle" value="bronze"> Bronze dark (deep tan)</a>
<a class="dropdown-item" href="#"><img src="img/tan.jpg" class="rounded-circle" value="tan"> Tan (warm to medium)</a>
<a class="dropdown-item" href="#"><img src="img/dark.jpg" class="rounded-circle" value="rich"> Rich (deep)</a>
</div>
</div>
<br>
<!--Result-->
<button type="button" class="btn btn-info btn-lg active" style="background-color: #3e4444;"> Submit</button>
JS:
function validate() {
var a =document.getElementById("eye_color").value;
var b =document.getElementById("skin_tone").value;
if (a == "green" && b == "fair"){
alert("Brown is your best hair color!!");
}
}

Here is a pure Javascript (no jQuery) example of what I think you have asked for.
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script>
document.onreadystatechange = function () {
if (document.readyState === "interactive") {
initApplication();
}
}
var eyeColor = null;
function selectMenu1(value){
eyeColor = value;
}
var skinTone = null;
function selectMenu2(value){
skinTone = value;
}
function validate() {
if (eyeColor && skinTone){
alert(`You selected ${eyeColor} eye colour and ${skinTone} skin tone.`);
//////////////////////////
//////////////////////////
//put your extra conditions below
//////////////////////////
//////////////////////////
if (eyeColor=="brown" && skinTone=="fair"){
alert("You should have w/e colour hair...");
} else if (eyeColor=="brown" && skinTone=="tan"){
alert("You should have w/e colour hair...");
}
}
else if (!eyeColor){
alert("Please pick an eye colour");
}
else if (!skinTone){
alert("Please pick a skin tone");
}
}
function initApplication(){
//setup dropdown menu selection events
Array.from(document.querySelectorAll(".dropdown-menu")).forEach((menu,idx)=>{
if (!menu.attributes.onchange) return;
const menuCallbackName = menu.attributes.onchange.value;
const fetchedCallback = window[menuCallbackName] || null;
if (fetchedCallback){
Array.from(menu.children).forEach((child)=>{
const callbackValue = child.attributes.data ? child.attributes.data.value : null;
if (callbackValue) child.onclick = () => fetchedCallback(callbackValue);
});
} else console.error(`No callback function named ${menuCallbackName} for menu ${idx}`);
});
}
</script>
</head>
<body>
<!--Drop down Item 1 -->
<h3 class="display-4" style="font-size: 1.5rem;">What is your eye color</h3>
<div class="dropdown">
<button class="btn btn-info btn-sm dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="background-color: #588c7e;">
Eye Color
</button>
<div class="dropdown-menu" onchange="selectMenu1" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#" data="brown"><img src="img/brown_eye.jpg" class="rounded-circle"> Brown</a>
<a class="dropdown-item" href="#" data="blue"><img src="img/blue_eye.jpg" class="rounded-circle" > Blue</a>
<a class="dropdown-item" href="#" data="green"><img src="img/green_eye.jpg" class="rounded-circle" > Green</a>
<a class="dropdown-item" href="#" data="hazel"><img src="img/hazel_eye.jpg" class="rounded-circle" > Hazel</a>
</div>
</div>
<!--Drop down Item 2-->
<h4 class="display-4" style="font-size: 1.5rem;"> What is your skin tone</h4>
<div class="dropdown">
<button class="btn btn-info btn-sm dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="background-color: #588c7e;">
Skin Tone
</button>
<div class="dropdown-menu" onchange="selectMenu2" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#" data="fair"><img src="img/fair.jpg" class="rounded-circle" > Fair (porcelain)</a>
<a class="dropdown-item" href="#" data="light"><img src="img/light.jpg" class="rounded-circle" > Light (fair to light)</a>
<a class="dropdown-item" href="#" data="medium"><img src="img/medium.jpg" class="rounded-circle" > Medium (light to medium)</a>
<a class="dropdown-item" href="#" data="bronze"><img src="img/bronze_dark.jpg" class="rounded-circle" > Bronze dark (deep tan)</a>
<a class="dropdown-item" href="#" data="tan"><img src="img/tan.jpg" class="rounded-circle" > Tan (warm to medium)</a>
<a class="dropdown-item" href="#" data="rich"><img src="img/dark.jpg" class="rounded-circle" > Rich (deep)</a>
</div>
</div>
<br>
<!--Result-->
<button type="button" class="btn btn-info btn-lg active" style="background-color: #3e4444;" onclick="validate()"> Submit</button>
</body>
</html>

Related

How to change the value of parent when i trigger a child?

I want to do something like a dropdown so that my user can pick whether they want gmail, hotmail, or outlook. And then, I want the button to update to show their preference. I must use bootstrap only and thus cannot use < select> due to assignment reasons.
So far, I've tried giving them all the same id, but JS just used the first one, and i dont want to give them all different IDs (too troublesome). So what I've written is to use the child number (like an array) and putting the value into the button. However, I have no idea how to find out the position number of the current html tag. Please help me and thank you for the help in advance
Bootstrap CDN used (Bootstrap 4.6.0):
link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"
<div class="input-group-append">
<button class="btn btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id='btnemailexample'>#example.com</button>
<div class="dropdown-menu" id='emailexample'>
<a class="dropdown-item" role='button' onclick='example()'>#gmail.com</a>
<a class="dropdown-item" role='button' onclick='example()'>#hotmail.com</a>
<a class="dropdown-item" role='button' onclick='example()'>#outlook.com</a>
<a class="dropdown-item" role='button' onclick='example()'>#yahoo.com</a>
</div>
</div>
<script>
function example() {
var c = document.getElementById('emailexample').children;
txt = c[i].textContent
document.getElementById("btnemailexample").innerHTML = txt;
}
</script>
This should do the trick!
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id='btnemailexample' data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
#example.com
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#" role='button' onclick='example(this)'>#gmail.com</a>
<a class="dropdown-item" href="#" role='button' onclick='example(this)'>#hotmail.com</a>
<a class="dropdown-item" href="#" role='button' onclick='example(this)'>#outlook.com</a>
<a class="dropdown-item" href="#" role='button' onclick='example(this)'>#yahoo.com</a>
</div>
</div>
<script>
function example(el) {
var txt = el.textContent;
document.getElementById("btnemailexample").innerHTML = txt;
}
</script>
In your case you don't need the search the id or the children, you can just use the event param.
<div class="input-group-append">
<button class="btn btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id='btnemailexample'>#example.com</button>
<div class="dropdown-menu" id='emailexample'>
<a class="dropdown-item" role='button' onclick='example(event)'>#gmail.com</a>
<a class="dropdown-item" role='button' onclick='example(event)'>#hotmail.com</a>
<a class="dropdown-item" role='button' onclick='example(event)'>#outlook.com</a>
<a class="dropdown-item" role='button' onclick='example(event)'>#yahoo.com</a>
</div>
</div>
<script>
function example(event) {
var txt = event.target.textContent;
document.getElementById("btnemailexample").innerHTML = txt;
}
</script>
A best solution in this case would be to use event delegation which will reduce your ID or Classes markup issue, adding function to every element, etc. It will help you get your required data as well.
Here is a good article on event delegation
You could do this a lot better if you have some JavaScript library like jQuery. I'll show you how to do it by both means.
Please note that I have not linked any styles. So make sure to link them for better viewability.
Using Core Javascript
// Add event listener to table
const el = document.getElementById("emailexample");
el.addEventListener("click", function(e) {
e = e || window.event;
var target = e.target || e.srcElement,
text = target.textContent || target.innerText;
document.getElementById("btnemailexample").textContent = text;
}, false);
<div class="input-group-append">
<button class="btn btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id='btnemailexample'>#example.com</button>
<div class="dropdown-menu" id='emailexample'>
<a class="dropdown-item" role='button'>#gmail.com</a>
<a class="dropdown-item" role='button'>#hotmail.com</a>
<a class="dropdown-item" role='button'>#outlook.com</a>
<a class="dropdown-item" role='button'>#yahoo.com</a>
</div>
</div>
Using jQuery
$("#emailexample .dropdown-item").on('click', function(e) {
e.preventDefault();
var text = $(this).text();
$("#btnemailexample").text(text);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group-append">
<button class="btn btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id='btnemailexample'>#example.com</button>
<div class="dropdown-menu" id='emailexample'>
<a class="dropdown-item" role='button'>#gmail.com</a>
<a class="dropdown-item" role='button'>#hotmail.com</a>
<a class="dropdown-item" role='button'>#outlook.com</a>
<a class="dropdown-item" role='button'>#yahoo.com</a>
</div>
</div>

Bootstrap dropdown menu stuck in expanded position, doesn't respond to button

I'm trying to make a simple sign in program for use in a podium at my office. All that this program is responsible for is allowing clients to put in their name, username, description of their problem, and click submit. this information will then get put into a CSV.
This all works fine, however the Bootstrap 4 dropdown menu I have included is always stuck open. It defaults to expanded when the page loads, and remains open regardless of clicking the button or not.
My code is almost exactly the same as the example code shown on Bootstraps site:
<div class="row">
<div class="col-sm">
<div class="dropdown">
<button class="btn btn-secondary btn btn-block dropdown-toggle" type="button" id="dropdownMenuButton"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Reason for your visit
</button>
<div class="col-sm">
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton" style="display: block">
<a class="dropdown-item" href="javascript:dropDownSelection('Scantron Dropoff')">Scantron dropoff</a>
<a class="dropdown-item" href="javascript:dropDownSelection('Scantron Pickup')">Scantron pickup</a>
<a class="dropdown-item" href="javascript:dropDownSelection('Wifi issues')">Wifi issues</a>
<a class="dropdown-item" href="javascript:dropDownSelection('DUO Enrollment issues')">DUO Enrollment issues</a>
<a class="dropdown-item" href="javascript:dropDownSelection('Password Issues')">Password issues</a>
</div>
</div>
</div>
</div>
</div>
And here are my imports:
<script src="node_modules/jquery/dist/jquery.js"></script>
<link rel="stylesheet"
href="node_modules/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="custom.css">
EDIT: This issue seems to only exist within the Electron/Node.JS enviornment. running my html/css within chrome (by launching the index.html file) works as expected and does not show any errors in the developer console.
"the Bootstrap 4 dropdown menu I have included is always stuck open"
The dropdown remains "open" because it has inline style "style:display:block". Remove this and follow the normal dropdown structure...
<div class="col-sm">
<div class="dropdown">
<button class="btn btn-secondary btn btn-block dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Reason for your visit
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="javascript:dropDownSelection('Scantron Dropoff')">Scantron dropoff</a>
<a class="dropdown-item" href="javascript:dropDownSelection('Scantron Pickup')">Scantron pickup</a>
<a class="dropdown-item" href="javascript:dropDownSelection('Wifi issues')">Wifi issues</a>
<a class="dropdown-item" href="javascript:dropDownSelection('DUO Enrollment issues')">DUO Enrollment issues</a>
<a class="dropdown-item" href="javascript:dropDownSelection('Password Issues')">Password issues</a>
</div>
</div>
</div>
Demo: https://www.codeply.com/go/ViKYGOigbL
You have to import bootstraps.bundle.js, too. Otherwise it will not toggle:
<script src="node_modules/bootstrap/dist/js/bootstrap.bundle.js"></script>
take note that you're importing jquery before importing boottsraps js-file
You also have to remove style="display: block" from your dropdown-menu. This display: block; is the reason why your menu stucks in expanded position.
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.bundle.min.js" integrity="sha384-pjaaA8dDz/5BgdFUPX6M/9SUZv4d12SUPF0axWc+VRZkx5xU3daN+lYb49+Ax+Tl" crossorigin="anonymous"></script>
<!-- imported jquery, bootstraps css and bootstraps bundle.js -->
<div class="row">
<div class="col-sm">
<div class="dropdown">
<button class="btn btn-secondary btn btn-block dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Reason for your visit
</button>
<div class="col-sm">
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<!-- removed style="display: block;" -->
<a class="dropdown-item" href="javascript:dropDownSelection('Scantron Dropoff')">Scantron dropoff</a>
<a class="dropdown-item" href="javascript:dropDownSelection('Scantron Pickup')">Scantron pickup</a>
<a class="dropdown-item" href="javascript:dropDownSelection('Wifi issues')">Wifi issues</a>
<a class="dropdown-item" href="javascript:dropDownSelection('DUO Enrollment issues')">DUO Enrollment issues</a>
<a class="dropdown-item" href="javascript:dropDownSelection('Password Issues')">Password issues</a>
</div>
</div>
</div>
</div>
</div>

Picture Change in Javascript

Well this doesn't worked for me and idk what to do so I ask you guys hopefully you can help me. Script is at the top, in the middle I add picture with id and I want to apply the change on a button below.
function pictureChange()
{
document.getElementById("theImage").src="https://cdn.glitch.com/6dc68b9b-62ee-49bb-904f-9bc85ead27a3%2Fhn%C4%9Bd%C3%A1-2.jpg?1539113123667";
}
<div style="padding-top:2%;padding-left:42.7%" class="row">
<img id="theImage" src="https://cdn.glitch.com/6dc68b9b-62ee-49bb-904f-9bc85ead27a3%2Fhn%C4%9Bd%C3%A1-2.jpg?1539091308847" style="width:300px;height:240px">
</div>
<center>
<div class="btn-group" style="padding-top:1%">
<button type="button" class="btn btn-danger" onclick="pictureChange()">Vyberte barvu</button>
<button type="button" class="btn btn-danger dropdown-toggle px-3" data-toggle="dropdown" aria-haspopup="true"
aria-expanded="false">
<span class="sr-only">Toggle Dropdown</span>
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">Hnědá</a>
<a class="dropdown-item" href="#">Lakované dřevo</a>
<a class="dropdown-item" href="#">Olej černá</a>
<a class="dropdown-item" href="#">Olej bílá</a>
<a class="dropdown-item" href="#">Šedá</a>
<a class="dropdown-item" href="#">Světle hnědá</a>
<a class="dropdown-item" href="#">Teak</a>
<a class="dropdown-item" href="#">Zelená</a>
</div>
</div>
</center>
You're trying to change it to the same picture as it was. It's actually working you can't just see it.

1 button is opening 2 dropdowns on bootstrap

I'm creating a 2 different dropdown, however, they're opening the same dropdown menu.
My code;
<div class="d-flex">
<button class="btn btn-icon btn-group-nav shadow-sm btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" data-offset="0 8" aria-haspopup="true" aria-expanded="false">
<span class="btn-inner--icon"><i class="far fa-sliders-h"></i></span>
<span class="btn-inner--text d-none d-md-inline-block">Sort by</span>
</button>
<div class="dropdown-menu dropdown-menu-left dropdown-menu-arrow">
<a class="dropdown-item" href="">Price</a>
<a class="dropdown-item" href="">Amount</a>
<a class="dropdown-item" href="">Number</a>
</div>
<button class="btn btn-icon btn-group-nav shadow-sm btn-secondary ml-auto dropdown-toggle" type="button" data-toggle="dropdown" data-offset="0 8" aria-haspopup="true" aria-expanded="false">
<span class="btn-inner--icon"><i class="far fa-user"></i></span>
<span class="btn-inner--text d-none d-md-inline-block">User</span>
</button>
<div class="dropdown-menu dropdown-menu-right dropdown-menu-arrow">
<a class="dropdown-item" href="account-settings.html">Settings</a>
<a class="dropdown-item" href="account-billing.html">Billing</a>
<a class="dropdown-item" href="account-notifications.html">Notifications</a>
</div>
</div>
How can I fix this?
As the documentation states and shows you:
Wrap the dropdown’s toggle (your button or link) and the dropdown menu
within .dropdown
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
<div class="d-flex">
<div class="dropdown">
<button class="btn btn-icon btn-group-nav shadow-sm btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" data-offset="0 8" aria-haspopup="true" aria-expanded="false">
<span class="btn-inner--icon"><i class="far fa-sliders-h"></i></span>
<span class="btn-inner--text d-none d-md-inline-block">Sort by</span>
</button>
<div class="dropdown-menu dropdown-menu-left dropdown-menu-arrow">
<a class="dropdown-item" href="">Price</a>
<a class="dropdown-item" href="">Amount</a>
<a class="dropdown-item" href="">Number</a>
</div>
</div>
<div class="dropdown">
<button class="btn btn-icon btn-group-nav shadow-sm btn-secondary ml-auto dropdown-toggle" type="button" data-toggle="dropdown" data-offset="0 8" aria-haspopup="true" aria-expanded="false">
<span class="btn-inner--icon"><i class="far fa-user"></i></span>
<span class="btn-inner--text d-none d-md-inline-block">User</span>
</button>
<div class="dropdown-menu dropdown-menu-right dropdown-menu-arrow">
<a class="dropdown-item" href="account-settings.html">Settings</a>
<a class="dropdown-item" href="account-billing.html">Billing</a>
<a class="dropdown-item" href="account-notifications.html">Notifications</a>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

How to get Javascript to change styles?

My JavaScript is not changing the attributes upon calling them from the "Change your style" button. It should change all four paragraphs under the images to a different style. Any assistance would be appreciated. I feel as if it's just a typo somewhere.
Here is my code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-
to-fit=no">
<title>Week4-1.html</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-
Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-
JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
<script src="../js/week4-1.js"></script>
<link rel="stylesheet" href="../css/homework.css">
</head>
<body>
<script src="../js/week4-1.js"></script>
<!--Navigation to different links and parts of the website-->
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<a class="navbar-brand" href="#">My Rummage Store</a>
<button class="navbar-toggler" type="button" data-toggle="collapse"
data-target="#navbarsExampleDefault" aria-
controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle
navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarsExampleDefault">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Products</a>
<div class="dropdown-menu" aria-labelledby="dropdown01">
<a class="dropdown-item" href="#">Rummage Items</a>
<a class="dropdown-item" href="#">Unique Items</a>
<a class="dropdown-item" href="#">Love that Ink Pen Company</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown02" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Who we are</a>
<div class="dropdown-menu" aria-labelledby="dropdown01">
<a class="dropdown-item" href="#">About Us</a>
<a class="dropdown-item" href="#">Our Vision</a>
<a class="dropdown-item" href="#">Contact Us</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown03" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Links</a>
<div class="dropdown-menu" aria-labelledby="dropdown01">
<a class="dropdown-item" href="../pages/home.html">Home</a>
<a class="dropdown-item" href="../pages/week1-1.html">Week 1-1</a>
<a class="dropdown-item" href="../pages/week1-2.html">Week 1-2</a>
<a class="dropdown-item" href="../pages/week2-1.html">Week 2-1</a>
<a class="dropdown-item" href="../pages/week2-2.html">Week 2-2</a>
<a class="dropdown-item" href="../pages/week3-1.html">Week 3-1</a>
<a class="dropdown-item" href="../pages/week3-2.html">Week 3-2</a>
<a class="dropdown-item" href="../pages/week4-1.html">Week 4-1</a>
<a class="dropdown-item" href="../pages/week4-2.html">Week 4-2</a>
<a class="dropdown-item" href="../pages/week5-1.html">Week 5-1</a>
<a class="dropdown-item" href="../pages/week5-2.html">Week 5-2</a>
<a class="dropdown-item" href="../pages/week6-1.html">Week 6-1</a>
<a class="dropdown-item" href="../pages/week6-2.html">Week 6-2</a>
<a class="dropdown-item" href="../pages/week7-1.html">Week 7-1</a>
<a class="dropdown-item" href="../pages/week7-2.html">Week 7-2</a>
<a class="dropdown-item" href="../pages/week8-1.html">Week 8-1</a>
<a class="dropdown-item" href="../pages/week8-2.html">Week 8-2</a>
</div>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Submit</button>
</form>
</div>
</nav>
<main role="main">
<!--Main jumbotron-->
<div class="jumbotron">
<div class="container">
<h1 class="display-3" style="text-align:center">Rummage Items</h1>
</div>
<!--Card to display a logo-->
<div class="card" style="width: 18rem; color:black">
<img class="card-img-top" src="../images/week2-1logo.jpg" alt="Card image cap">
<div class="card-body">
<h5 class="card-title"></h5>
<p class="card-text">Rummage it</p>
</div>
<!--Button to change paragraph font-->
<p>
<button type="button" onclick="changeStyles();" class="btn btn-primary btn-lg">Change the Style</button>
</p>
</div>
</div>
<!--Improved columns--->
<div class="container-fluid">
<button type="button" onclick="changeStyles();" class="btn btn-primary btn-lg">Change the Paragraph Style</button>
<div class="row">
<div class="col-md-3 home_box_border home_box_corner home_box_shadow home_box_gradient" div style="text-align:center; vertical-align:middle">
<hr />
<h2>Printers</h2>
<img class="img-circle1" src="../images/product4.jpg" alt="print" align="middle">
<p class="week4-1_Printers">The HPSR printer has a direct feed for over 30 different types of paper. Allowing for ultimate utilization. It also showcases the new style of modern printers. Multifunction printers allow for use of communication via fax.</p>
<p><a class="btn btn-secondary" href="#" role="button">Buy for $299.99 »</a></p>
</div>
<div class="col-md-3 home_box_border home_box_corner home_box_shadow home_box_gradient" div style="text-align:center; vertical-align:middle">
<hr />
<h2>Boots</h2>
<img class="img-circle1" src="../images/product3.jpg" alt="boots">
<p class="week4-1_Boots">The new rummage boot collection. Hand crafted leather for the ultimate rummaging experience. Your feet will thank you during your next rummaging expedition! We look forward to helping you try them on. </p>
<p><a class="btn btn-secondary" href="#" role="button">Buy for $69.99 »</a></p>
</div>
<div class="col-md-3 home_box_border home_box_corner home_box_gradient home_box_shadow" div style="text-align:center; vertical-align:middle">
<hr />
<h2>Lamps</h2>
<img class="img-circle1" src="../images/product5.jpg" alt="Lamp">
<p class="week4-1_Lamps">Lamps are a neccesity during night time. This lamp is hand crafted and made from the finest craftsman we could find. You will not regret buying this lamp, adding a nice piece of decor and bringing some brigtness in your life. </p>
<p><a class="btn btn-secondary" href="../pages/week1-2.html" role="button"> Buy for $39.99 »</a></p>
</div>
<div class="col-md-3 home_box_border home_box_corner home_box_gradient home_box_shadow" div style="text-align:center; vertical-align:middle">
<hr />
<h2>Dressers</h2>
<img class="img-circle1" src="../images/product2.jpg" alt="Lamp">
<p class="week4-1_Dressers">Our Dressers are one of a kind. We have so many variations that you can rummage through and find. Purchase on our site or come in today and take a look! Very sturdy and made with some of the best wood you can buy. </p>
<p><a class="btn btn-secondary" href="../pages/week1-2.html" role="button"> Buy for $239.99 »</a></p>
</div>
</div>
</div>
</main>
<!-- Footer Information -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
Here is my js:
function injectStyles(rule) {
var div = $("<div />", {
html: '­<style>' + rule + '</style>'
}).appendTo("body")
}
function changeStyles() {
// alert("Hi");
// injectStyles('p { color: red; }');
injectStyles('.week4-1_Printers { border: 10px solid black; font-weight:
500; color: darkblue; border-radius: 10px; }');
injectStyles('.week4-1_Boots { border:10px solid black; font-weight: 500;
color: darkblue; border-radius: 10px; }');
injectStyles('.week4-1_Lamps { border:10px solid black; font-weight: 500;
color: darkblue; border-radius: 10px; }');
injectStyles('.week4-1_Dressers { border:10px solid black; font-weight: 500;
color: darkblue; border-radius: 10px; }');
}
I will update the
function injectStyles(rule) {
$("head").append('<style>' + rule + '</style>');
}
to append style in the head.
I don't think that your issue is with the button, as the code is being executed.
Instead of writing div elements why not just change the style directly? I changed your injectStyles function to accept two arguments: the class name of the elements you want to change and a JavaScript object that contains all the style values you want to set. Then, I just loop through every element that matches the class name, then set the style for every node in the style definition.
(you need to go into full screen to see the snippet work)
function injectStyles(className, styles) {
var elements = document.getElementsByClassName(className);
// loop through every element
for(var i=0; i < elements.length; i++) {
// loop through every style
for(var style in styles) {
elements[i].style[style] = styles[style];
}
}
}
function changeStyles() {
injectStyles('week4-1_Printers', { "border": "10px solid black", "font-weight": "500", "color": "darkblue", "border-radius": "10px" } );
injectStyles('week4-1_Boots', { "border": "10px solid black", "font-weight": "500", "color": "darkblue", "border-radius": "10px" } );
// injectStyles('.week4-1_Lamps { border:10px solid black; font-weight: 500; color: darkblue; border-radius: 10px; }');
// injectStyles('.week4-1_Dressers { border:10px solid black; font-weight: 500; color: darkblue; border-radius: 10px; }');
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-
to-fit=no">
<title>Week4-1.html</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-
Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-
JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
<script src="./script.js"></script>
<link rel="stylesheet" href="../css/homework.css">
</head>
<body>
<script src="../js/week4-1.js"></script>
<!--Navigation to different links and parts of the website-->
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<a class="navbar-brand" href="#">My Rummage Store</a>
<button class="navbar-toggler" type="button" data-toggle="collapse"
data-target="#navbarsExampleDefault" aria-
controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle
navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarsExampleDefault">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Products</a>
<div class="dropdown-menu" aria-labelledby="dropdown01">
<a class="dropdown-item" href="#">Rummage Items</a>
<a class="dropdown-item" href="#">Unique Items</a>
<a class="dropdown-item" href="#">Love that Ink Pen Company</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown02" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Who we are</a>
<div class="dropdown-menu" aria-labelledby="dropdown01">
<a class="dropdown-item" href="#">About Us</a>
<a class="dropdown-item" href="#">Our Vision</a>
<a class="dropdown-item" href="#">Contact Us</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown03" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Links</a>
<div class="dropdown-menu" aria-labelledby="dropdown01">
<a class="dropdown-item" href="../pages/home.html">Home</a>
<a class="dropdown-item" href="../pages/week1-1.html">Week 1-1</a>
<a class="dropdown-item" href="../pages/week1-2.html">Week 1-2</a>
<a class="dropdown-item" href="../pages/week2-1.html">Week 2-1</a>
<a class="dropdown-item" href="../pages/week2-2.html">Week 2-2</a>
<a class="dropdown-item" href="../pages/week3-1.html">Week 3-1</a>
<a class="dropdown-item" href="../pages/week3-2.html">Week 3-2</a>
<a class="dropdown-item" href="../pages/week4-1.html">Week 4-1</a>
<a class="dropdown-item" href="../pages/week4-2.html">Week 4-2</a>
<a class="dropdown-item" href="../pages/week5-1.html">Week 5-1</a>
<a class="dropdown-item" href="../pages/week5-2.html">Week 5-2</a>
<a class="dropdown-item" href="../pages/week6-1.html">Week 6-1</a>
<a class="dropdown-item" href="../pages/week6-2.html">Week 6-2</a>
<a class="dropdown-item" href="../pages/week7-1.html">Week 7-1</a>
<a class="dropdown-item" href="../pages/week7-2.html">Week 7-2</a>
<a class="dropdown-item" href="../pages/week8-1.html">Week 8-1</a>
<a class="dropdown-item" href="../pages/week8-2.html">Week 8-2</a>
</div>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Submit</button>
</form>
</div>
</nav>
<main role="main">
<!--Main jumbotron-->
<div class="jumbotron">
<div class="container">
<h1 class="display-3" style="text-align:center">Rummage Items</h1>
</div>
<!--Card to display a logo-->
<div class="card" style="width: 18rem; color:black">
<img class="card-img-top" src="../images/week2-1logo.jpg" alt="Card image cap">
<div class="card-body">
<h5 class="card-title"></h5>
<p class="card-text">Rummage it</p>
</div>
<!--Button to change paragraph font-->
<p>
<button type="button" onclick="changeStyles();" class="btn btn-primary btn-lg">Change the Style</button>
</p>
</div>
</div>
<!--Improved columns--->
<div class="container-fluid">
<button type="button" onclick="changeStyles();" class="btn btn-primary btn-lg">Change the Paragraph Style</button>
<div class="row">
<div class="col-md-3 home_box_border home_box_corner home_box_shadow home_box_gradient" div style="text-align:center; vertical-align:middle">
<hr />
<h2>Printers</h2>
<img class="img-circle1" src="../images/product4.jpg" alt="print" align="middle">
<p class="week4-1_Printers">The HPSR printer has a direct feed for over 30 different types of paper. Allowing for ultimate utilization. It also showcases the new style of modern printers. Multifunction printers allow for use of communication via fax.</p>
<p><a class="btn btn-secondary" href="#" role="button">Buy for $299.99 »</a></p>
</div>
<div class="col-md-3 home_box_border home_box_corner home_box_shadow home_box_gradient" div style="text-align:center; vertical-align:middle">
<hr />
<h2>Boots</h2>
<img class="img-circle1" src="../images/product3.jpg" alt="boots">
<p class="week4-1_Boots">The new rummage boot collection. Hand crafted leather for the ultimate rummaging experience. Your feet will thank you during your next rummaging expedition! We look forward to helping you try them on. </p>
<p><a class="btn btn-secondary" href="#" role="button">Buy for $69.99 »</a></p>
</div>
<div class="col-md-3 home_box_border home_box_corner home_box_gradient home_box_shadow" div style="text-align:center; vertical-align:middle">
<hr />
<h2>Lamps</h2>
<img class="img-circle1" src="../images/product5.jpg" alt="Lamp">
<p class="week4-1_Lamps">Lamps are a neccesity during night time. This lamp is hand crafted and made from the finest craftsman we could find. You will not regret buying this lamp, adding a nice piece of decor and bringing some brigtness in your life. </p>
<p><a class="btn btn-secondary" href="../pages/week1-2.html" role="button"> Buy for $39.99 »</a></p>
</div>
<div class="col-md-3 home_box_border home_box_corner home_box_gradient home_box_shadow" div style="text-align:center; vertical-align:middle">
<hr />
<h2>Dressers</h2>
<img class="img-circle1" src="../images/product2.jpg" alt="Lamp">
<p class="week4-1_Dressers">Our Dressers are one of a kind. We have so many variations that you can rummage through and find. Purchase on our site or come in today and take a look! Very sturdy and made with some of the best wood you can buy. </p>
<p><a class="btn btn-secondary" href="../pages/week1-2.html" role="button"> Buy for $239.99 »</a></p>
</div>
</div>
</div>
</main>
<!-- Footer Information -->
If you want to keep the styles as a string you could parse it into an array using styles.split('delimiter'), but defining it as a JavaScript object makes it super-easy to process.

Categories

Resources