Inject css inline into elements using js - javascript

For example, my html code is as follows:
<html lang="en">
<head>
<meta charset="utf-8">
<title>add style inline in js</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<div class="one">
<div class="two">
link
</div>
</div>
<script src="js/my-scripts.js"></script>
</body>
</html>
I want to select elements and style them in my-scripts.js file like css:
.one .two a:hover{color:red;}
I have a sample jquery code:
function injectStyles(rule) {
var div = $("<div />", {
html: '­<style>' + rule + '</style>'
}).appendTo("body");
}
$("button").on("click", function() {
injectStyles('a:hover { color: red; }');
});
https://css-tricks.com/snippets/javascript/inject-new-css-rules/
but I want to do this without using jquery and without using the button.
(Apply styles after loading script file)
I want to define my css code in js and define each one separately as "inline" for each element.
Thanks to the professors

You could create a template class in your css file like this
.colorOnHover a:hover {
color: red;
}
And then you can use document.querySelector to get the element and add the colorOnHover to the classList of that element.
// your js file
const element = document.querySelector(''); // pass in the ID or the class of the element you want to add the changes to
(function() {
element.classList.add('colorOnHover');
})();
// this will add `colorOnHover` class to the classList and apply the css defined to the class in your css file.
Make sure to link the javascript & css file (if any) using <script src = "pathHere" defer></script> and <link rel = 'stylesheet' href = "pathHere>" respectively
update : since the op didn't want to use querySelector
You could use document.createElement('style') and append it to the html file, it would be similar to manually inserting a tag
(function() {
const styleEl = document.createElement('style');
styleEl.textContent = '.one .two a:hover{color:red;}';
document.head.append(styleEl);
console.log('added new style tag');
})();

This how to inject your CSS to to <style> tag :
JS & jQuery code :
function injectStyles(rule) {
$("style").append(rule);
}
$("button").on("click", function() {
injectStyles('.one .two a:hover{color:red;}');
});
HTML code :
<html lang="en">
<head>
<meta charset="utf-8">
<title>add style inline in js</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js" integrity="sha512-n/4gHW3atM3QqRcbCn6ewmpxcLAHGaDjpEBu4xZd47N0W2oQ+6q7oc3PXstrJYXcbNU1OHdQ1T7pAP+gi5Yu8g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<div class="one">
<div class="two">
link<br>
<button type="button">Make the link hover Red</button>
</div>
</div>
<script src="js/my-scripts.js"></script>
</body>
</html>

Related

getElementById does not call the HTML ID

I have a folder with two files each, once the HTML file, and once the JS file to make everything clearer. My problem now is that I try to access an ID within the HTML file with the getElementById but this doesn't seem to work.
var score = 0;
score = score + 1;
document.getElementById("score").outerHTML = score;
<!DOCTYPE html>
<head>
<title>Clicker Game</title>
<link rel="stylesheet" href="design.css">
<script src="code.js" type="text/javascript"></script>
</head>
<body>
<p>Cookies: <span id="score">0</span></p>
<img src="images/cookie.png" height="256px" width="256px">
</body>
</html>
I am trying to call the ID "score" in the HTML file to make sure that when I start the HTML file locally the number changes from 0 to 1.
Click on the number in the HTML file, which will change the value. You cannot change the value without a trigger in the HTML. Something needs to be clicked or changed for the value to appear.
Edit: And don't grab the outerHTML of the element. You are erasing the whole score span and replacing it with the count. Use textContent instead.
let elem = document.querySelector("#score");
elem.addEventListener("click", (e) => {
elem.textContent = Number(elem.textContent) + 1;
})
#score {
cursor: pointer;
}
<!DOCTYPE html>
<head>
<title>Clicker Game</title>
<link rel="stylesheet" href="design.css">
<script src="code.js" type="text/javascript" defer></script>
</head>
<body>
<p>Cookies: <span id="score">0</span></p>
<img src="images/cookie.png" height="256px" width="256px">
</body>
</html>

Trying to use Javascript to change img src in HTML

I'm trying to use Javascript to change the src attribute of an image (id: big-img) to that of a smaller image (class: clicky) when the smaller image is clicked to create . Unfortunately it doesn't seem to be working. Code provided below.
HTML:
<!DOCTYPE HTML>
<html lang="en">
<head>
<!-- Always use meta tags in head first -->
<!-- Sets character encoding (utf-8 = unicode) -->
<meta charset="utf-8">
<!-- Sets width of the page to width of the device and sets initial zoom
value to 1.0. Used for mobile viewing -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Linking in bootstrap (css) and author styles. -->
<link type="text/css" rel="stylesheet" href="css/bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="css/styles.css">
</head>
<body>
<!-- For simple Javascript concept exercises -->
<div id="practice">
<p>
Does this work?
</p>
</div>
<!-- For image related complex(ish) Javascript exercises -->
<div class="container">
<div class="row">
<div class="clicky col-md-3"><img src="img/img1.jpg"></div>
<div class="clicky col-md-3"><img src="img/img2.jpg"></div>
<div class="clicky col-md-3"><img src="img/img3.jpg"></div>
<div class="clicky col-md-3"><img src="img/img4.jpg"></div>
</div>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<img id="big-img"
class="large-img"
src="img/img1.jpg">
</div>
</div>
</div>
<!-- <div class="col-md-12">
<img id="bigImage"
class="large-img"
src="img_1.jpg"
alt="graffittied building"/>
</div> -->
<!-- Linking in Jquery library, bootstrap (JS) and my scripts. Imported in
that order due to bootstrap requiring some Jquery features so needs to be
lower in source order -->
<script type="text/javascript" src="js/jquery-2.1.4.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/scripts.js"></script>
</body>
</html>
Javascript:
$(".clicky").click(function(){
$("#big-img").attr('src',
$(this).attr('src'));
});
As clicky is not img element it doesn't have src attribute thus the code is working as expected.
You need to traverse to img element the fetch its attribute, there are various ways to achieve that. Here in code I have used .find() method since img is child of clicky element
$(".clicky").click(function(){
$("#big-img").attr('src', $(this).find('img').attr('src'));
});
OR, You can bind event with img element then your code will work
$(".clicky img").click(function(){
$("#big-img").attr('src', this.src);
//$("#big-img").attr('src', $(this).attr('src'));
});
function change_img(){
$(document).on("click",".clicky img",function(){
var el = $(this);
var src = $.trim(el.attr("src"));
(src !=="") ? $("#big-img").attr("src",src) : '';
});
}
$(function(){
change_img();
});
Try this:
$(".clicky").click(function(){
$("#big-img").attr('src',
$(this).find('img').attr('src'));
});
clicky class is attached to a div not to an img so it does not have a src attribute
What you can do is this:
$(".clicky > img").click(function(){
$("#big-img").attr('src', $(this).attr('src'));
});
But if you want to to attach the listener on the div, you can do this:
$(".clicky").click(function(){
$("#big-img").attr('src', $(this).find("img").attr('src'));
});
$(this) refers to the clicked element : <div>. You need to get img thats inside the div.
$(".clicky").click(function(){
$("#big-img").attr('src',$('img', this).attr('src'));
});
To complete :
$(".clicky").on('click', function(e){
$("#big-img").attr('src',$('img', this).attr('src'));
});

Show image via javascript after page load

I am trying to create an image which is initially hidden - but reveals itself once the document has loaded completely via the JavaScript file.
$(document).ready(function () {
document.getElementById("theImage").style.visibility = "visible";
});
#theImage {
visibility:hidden;
}
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kami Nelson Bio </title>
<link href="boilerplate.css" rel="stylesheet" type="text/css">
<link href="KNelson-Styles.css" rel="stylesheet" type="text/css">
<script src="respond.min.js"></script>
<script src="KNelson_reveal.js"></script>
</head>
<body>
<div class="gridContainer clearfix">
<div id="theImage">
<img src="images/Kami-100.jpg" alt="Kami Nelson Image"/>
</div>
<div id="div1" class="fluid">
<h1>Bio for Kami Nelson</h1>
<p>Text</p>
</div>
</div>
</body>
</html>
Why is this not working?
Thank you in advance.
You should either include jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Or use native window.onload() instead of $(document).ready()
window.onload=function () {
document.getElementById("theImage").style.visibility = "visible";
}
You are missing the jQuery library reference
You are not properly
using selecter to select image of id theImage.
theImage is supposed to be for the img tag.
JavaScript
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
$("#theImage").css('display':'block');
});
</script>
CSS
#theImage {
display: none;
}
HTML
<img id= "theImage" src="images/Kami-100.jpg" alt="Kami Nelson Image"/>
why don't you just draw the image when the window loads?
give your image an id i'll use "image" for this example.
<script>
window.onload = function ()
{
$('#image').css({"display":"block";});
}
</script>

Javascript replace text function

This is my javascript for replacing some text:
document.body.innerHTML = document.body.innerHTML.replace(/Sometext/g, 'difference');
Ho do I change color, font-size, font and such?
I need to link my script like this, can't use { otherwise:
<script>$(document).ready($.getScript("url"));</script>
I though something like this would work:
window.onload = function() {
document.body.innerHTML =
document.body.innerHTML.replace(/Deckling/g, result);
}
var str = "The Liberator";
var result = str.fontcolor("Red").italics().fontsize(6);
result.style.fontFamily = "Harrington";
Any help? (first post and very limited Knowledge)
You can wrap you text in a div or span tag, select it in JS applying a class.
The class will contains the style for your text.
Just a quick example in vanilla javaScript (no jquery):
http://jsbin.com/yufiteseme/1/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.a {
color:red;
font-style: italic;
font-size: 6px;
{
</style>
<script>
function changeColor(){
document.getElementById('text').classList.add('a');
}
</script>
</head>
<body onload="changeColor()">
<div id="text">
Test for example
</div>
</body>
</html>
You can change style of an html element using javascript, put your script below the element.
The following example changes the style of a 'p' element using javascript:
<!DOCTYPE html>
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").style.color = "red";
document.getElementById("p1").style.fontFamily = "Arial";
document.getElementById("p1").style.fontSize = "larger";
</script>
</body>
</html>
You can also change style of an html element using jquery.
The following example changes the style of a 'p' element using jquery:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$('#p1').ready(function(){
$('#p1').css({"color": "green"}).css({"fontFamily": "Arial"}).css({"fontSize": "24px"});
});
</script>
</head>
<body>
<p id="p1">Hello World!</p>
</body>
</html>
That will not work:
var result = str.fontcolor("Red").italics().fontsize(6);.
You need to add css to change the surface.Add this to your header:
.textstyle{
font-size:16px;
font-family:Harrington;
}
</style>
And add this to your window.onload:$('body').addClass('textstyle');

jQuery add class when button is clicked

When i click one of the buttons i want the paragraphs to change size depending on the button i've clicked. That doesn't seem to work. I've checked everything and with my level of knowledge of jQuery (beginner ) i can't figure it out so i need your help. Here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<input type="button" id="smaller" value="smaller text" />
<input type="button" id="bigger" value="bigger text" />
<p > Some text inside of it.</p>
<p > Some text inside of it too!</p>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="query.js"> </script>
</body>
</html>
jQuery
$('#bigger').click(function() {
$('p').addClass('.bigger');
});
$('#smaller').click(function() {
$('p').addClass('.smaller');
});
CSS
.bigger {
font-size:30px;
background-color:red;
}
.smaller {
font-size:10px;
}
Remove . from addClass() because the function already recognize the string like a class without specifiy the class selector.
try this:
$('#bigger').click(function() {
$('p').addClass('bigger'); //instead of .bigger
});
$('#smaller').click(function() {
$('p').addClass('smaller'); //instead of .smaller
});
DEMO
Remember $.addClass("bigger"); not $.addClass(".bigger");
Demo
http://jsfiddle.net/dieegov/ebGQ2/

Categories