document.getElementById('ID').style.cursor not working as expected - javascript

Why is the if statement not working here:
<!DOCTYPE html>
<html>
<body>
<style>#myP{cursor:pointer;}</style>
<p id="myP">random text</p>
<button type="button" onclick="myFunction()">alert aaa</button>
<script>
function myFunction(){
if(document.getElementById("myP").style.cursor=="pointer"){
alert("aaa");
}
}
</script>
</body>
</html>
Also, I want to know how to make the if statement work with a linked cursor like:
<style>#myP{cursor: url(../randomFolder/cursor.png) 5 8, auto;}</style>

Use this instead :
if (window.getComputedStyle(document.getElementsByTagName('body')[0]).cursor == 'pointer')

.style only works for inline CSS. window.getComputedStyle() will let you retrieve styles set via non-inline CSS.
For your second question, matching the linked image cursor is a little trickier than just matching a simple string like "pointer", because you're including a path which will be canonicalized to the full URL, as you can see below ("https://stacksnippets.net" is included in the path even though it wasn't specified in the CSS.) It's probably best to test for a substring of the full cursor value, so you don't run into problems where your code works on "yourdomain.com" but not on "www.yourdomain.com":
var myFunction = function() {
var A = document.getElementById('a');
var B = document.getElementById('b');
console.log(window.getComputedStyle(A).cursor);
console.log(window.getComputedStyle(B).cursor);
if (window.getComputedStyle(A).cursor == 'pointer') {
console.log("A matched");
}
var bCursor = window.getComputedStyle(B).cursor;
if (bCursor.indexOf('cursor.png') > -1) { // not hardcoding the full URL here
console.log("B matched");
}
}
#a {
cursor: pointer
}
#b {
cursor: url(randomFolder/cursor.png) 5 8, auto;
}
<p id="a">random text</p>
<p id="b">more random text</p>
<button onclick="myFunction()">alert</button>

You can use jQuery with css function and it will return you the kind of cursor which you need in a short code.
$('#myP').css('cursor')

Related

Trying to understand this toggleClass() function

The function in question:
function toggleElementClass(element, className) {
if (element.className.indexOf(className) > -1) {
element.className = element.className.replace(new RegExp(className, 'g'), '');
} else {
element.className += " " + className;
}}
I'm trying to identify issues with this code. I've had experience with jQuery and JavaScript here and there, but I cannot seem to come to a solid conclusion with what I've seen so far. I've seen a lot of examples using the current .toggleClass() function from jQuery but none that help me analyze the code above.
One problem I think I can identify is that it never seems to remove a class. Only adds more but I've had problems attempting to test this on plunker. Any help would be appreciated. What problems can you identify with this method?
Want to make an edit: This questions is purely for my own understanding. I'm not intending to use this or re-write a tool that already exists in jQuery! Thanks for all who have submitted answers so far!
Edit: For anyone who may be interested. This isn't a perfect solution (adds spaces between classes the more you toggle). It seems to get around the false positive the original code would cause!
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<h1 class="football">Hello Plunker!</h1>
<script>
function toggleElementClass(element, className) {
var regex = new RegExp('\\b' + className + '\\b', 'g');
if (regex.test(element.className)) {
element.className = element.className.replace(regex, '');
} else {
element.className += " " + className;
};
};
$("h1").click(function() {
toggleElementClass(this, "test")
})
</script>
</body>
</html>
The logic is fine for most circumstances, although will get false positives when searching for foo and a football class is available.
The specific issue with your code is with how you are attaching the click event to the h1. Currently you're setting the result of the function call to the event handler, not the function reference. This means the function is called immediately on load and the scope is not what you're expecting (it's the window instead of the h1) hence the 'undefined' error you receive.
To fix this you need to wrap the click event handler in an anonymous function:
function toggleElementClass(element, className) {
if (element.className.indexOf(className) > -1) {
element.className = element.className.replace(new RegExp(className, 'g'), '');
} else {
element.className += " " + className;
};
};
$("h1").click(function() {
toggleElementClass(this, "a")
})
.a {
color: #c00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="a">Hello Plunker!</h1>
That being said the function is completely redundant, as you can use either jQuery's toggleClass():
$("h1").click(function() {
$(this).toggleClass('a')
})
.a {
color: #c00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="a">Hello Plunker!</h1>
Or alternatively you can use classList.toggle():
document.querySelector('h1').addEventListener('click', function() {
this.classList.toggle('a');
});
.a {
color: #c00;
}
<h1 class="a">Hello Plunker!</h1>
Here are some problems:
You'll get false positives for a partial class name match (searching for foo, will match foobar). If you fix this problem, be careful how you do it, since you must allow for more than one kind of space separator.
The replacement will leave extra spaces, which isn't huge, but can add up.
You're using a regular expression with the assumption that the class name will not contain any special regex characters. You already are getting the index, so why not use that? You'll need a loop to make sure they all get removed, but it's going to be safer.

How to set font style "italic" using javascript

i know how to set font style italic in HTML but now i'm trying to do that only with java script . Is it possible to do that in java script ? . Can someone help\clarify me pls . Here is my code ,
myJson.name.push(mainSteps.name); // Need to changes this in italic (js code)
A JavaScript string itself doesn't have a concept of a "style". Styling only applies when you output the string somewhere. If you output it to HTML, you can use HTML or CSS to style it.
So if you are asking whether there is an "output-agnostic" way to style a JavaScript string, the answer is no.
Btw, the code you wrote is JavaScript (assuming you pass a proper value for the ID):
document.getElementById(#Html id).style.fontStyle = "italic";
and if you want to style the HTML output, then this would be the way to go.
In Javascript you can not change font style because it does not exist in javascript as such. Font style matters only when the data has to be shown which is when it is written on some where in HTML .This is how you may change the fontstyle for entire body
This is in italics
<script>
function italicsBody() {
document.body.style.fontStyle = "italic";
}
italicsBody()
</script>
Similary if you want the same for specifi data you may do it using getElemenById . Check the following code
<ul id="names">
</ul>
<script>
function italicsBody() {
document.getElementById("names").style.fontStyle = "italic";
}
function populateNames() {
var names = ["name1","name","name3"]
var nameList = document.getElementById("names");
for (var key in names) {
nameList.innerHTML = nameList.innerHTML + ' <li> ' + names[key] + '</li>';
}
}
populateNames()
italicsBody()
</script>
Here is the jsfiddle for the same jsfiddle
document.getElementById("myP").style.fontStyle = "italic";
You can use "somestring".italics() to get "<i>somestring</i>"which might be what you are after. I suggest you use CSS as others said though - italics is not standard anymore.
I Given One Example As Below
function myFunction() {
document.getElementById("myP").style.font = "italic 15px arial,serif";
}
myFunction();
<p id="myP">This is a paragraph.</p>
This Is Second Example When User Click On Button Then Style Applying From Java script .
function myFunction() {
document.getElementById("myP").style.font = "italic 20px arial,serif";
}
<p id="myP">This is a paragraph.</p>
<button type="button" onclick="myFunction()">Set font</button>
myJson.name.push(mainSteps.name).style.fontStyle = "italic";
It is done the same way.

How to pull css attributes from

I'm trying to figure out how to pull attributes from CSS to be used in Javascript. I've googled what I'm looking for so many times and in so many ways my fingers are about to fall off.
I'm looking to change font size to three different font sizes: 15px, 28px, and 40px. This would be toggled using three buttons. However, when you choose a font size, some of the other CSS attributes need to change in order to resize the text and padding to align with the element "behind" it, so that it doesn't push off the side and look ugly. I'm planning on doing the resizing automatically with Javascript, but for the life of me I can't figure out how to pull the "text size in pixels" attribute from the page in order to apply an "if/else" argument. This would need to be done in browser and I've found a .getComputedStyle command. But as I can't get it to work I'm not sure if that's what I need or not.
<body>
<p id="spaz">Text to be resized.</p>
<button type="button" onclick="txtszl()">large</button>
<button type="button" onclick="txtszm()">medium</button>
<script>
function txtszl(){
document.getElementById("spaz").style.fontSize="40px";
}
function txtszm(){
document.getElementById("spaz").style.fontSize="28px";
}
var $txtelement = document.getElementById("spaz");
var $txtsize = $txtelement.getComputedStyle("fontSize");
if ($txtsize == 40px){
alert("It's forty!");
}else{
alert("Nope!");
}
</script>
</body>
That's what I have come up with. Any help/links would be greatly appreciated!
The getComputedStyle function returns a CSSStyleDeclaration.
var txtElementStyles = getComputedStyle($txtelement, null),
fontSize = txtElementStyles.getPropertyValue('font-size');
Working fiddle: http://jsfiddle.net/wrathchild77/6LJaM/
function txtszl() {
document.getElementById("spaz").style.fontSize = "40px";
check();
}
function txtszm() {
document.getElementById("spaz").style.fontSize = "28px";
check();
}
function check() {
var $txtsize = document.getElementById("spaz").style.fontSize;
if ($txtsize == "40px") {
alert("It's forty!");
} else {
alert("Nope!");
}
}

how to make javascript function call two divs

i am trying to make a colour change when a button is clicked and i managed to do this however i want to change the colour of not just the main content container but more containers how do i do this?
function changeblackandwhite(objDivID) {
if(document.getElementById(objDivID).style.color=='black'){
document.getElementById(objDivID).style.color='white';
document.getElementById(objDivID).style.backgroundColor='black';
}
else if(document.getElementById(objDivID).style.color=='white'){
document.getElementById(objDivID).style.color='black';
document.getElementById(objDivID).style.backgroundColor = 'white';
}
else{
document.getElementById(objDivID).style.color='black';
document.getElementById(objDivID).style.backgroundColor='white';
}
}
<img src="images/colour.jpg" title="Change Text/Backgroud Colors">
There are dozens of ways you can accomplish this.
You could change the argument of your function to be an array of strings. You could also reduce the complexity of your function as well
<script type="text/javascript">
changeblackandwhite = function() {
for( var idx=0; idx < arguments.length; idx++) {
var tgtDiv= document.getElementById(arguments[i]);
if(tgtDiv.style.color=='black'){
tgtDiv.style.color='white';
tgtDiv.style.backgroundColor='black';
}
else{
tgtDiv.style.color='black';
tgtDiv.style.backgroundColor='white';
}
}
};
</script>
<img src="images/colour.jpg" title="Change Text/Backgroud Colors">
As another reader questioned - you can do this with jQuery in a single line.
With jQuery, you can declare the elements in question to have a class attribute.
Using jQuery, you can then do something like:
$('div.someClass').css({'color': 'black', 'background-color': 'white'});
The argument to jQuery can be a class based selector, an id based selector, or any other selector you choose.
If you are open to jquery and you assign 1 class in common with these two divs you can do the following:
This should get you started (see this jsfiddle): I changed the fiddle to include a neater solution where clicking on the button adds and removes classes on the containers which allows you to set multiple attributes including the text color in one quick call.
<div class='container'>
</div>
<div class='container'>
</div>
<button id="changeColor" type="button">Change Color </button>
<script type="text/javascript">
$(document).ready( function() {
$('#changeColor').click( function() {
if ($('.container').hasClass("blackContainer")){
$('.container').addClass("whiteContainer");
$('.container').removeClass("blackContainer");
} else {
$('.container').removeClass("whiteContainer");
$('.container').addClass("blackContainer");
}
});
});
</script>
//CSS
.blackContainer {
background-color: black;
color: white;
}
.whiteContainer {
background-color: white;
color: black;
}
I made a jsfiddle for you to play around with jsfiddle
I also did the javascript/jQuery in a similar way as the OP since it usually helps them understand.
As stated above, there are several different ways to do this, I've done but one.
The document.ready function sets up an event listener for the object to be clicked, most of the time this is how you'll see events coded. So when the link is clicked, it calls the function with the string name of the object the listener is for.
$(document).ready(function() {
$("#changeit").click(function(){
changeblackandwhite("Maincontainer");
})
});
After the event listener is assigned, it will call the function below when the link is clicked on.
// Here's your function, put the current color in a var, check if it's black
// if black, change colors, else make it black.
function changeblackandwhite(objDivID) {
var curColor = $("#" + objDivID).css("color");
if( curColor == 'rgb(0, 0, 0)'){
$("#"+objDivID).css({'color':'white','background-color':'black'});
} else {
$("#"+objDivID).css({'color':'black','background-color':'ghostwhite'});
}
}

Checking color value in javascript

So I set the color of the <body> with:
body
{
color:Black;
}
within the <head> and <style> tags,
and then I've got various elements in the body, for which if I click them, they call a function. i.e.
<p id="CSE1020" onclick="prereq(this)">CSE1020</p>
The prereq function is as follows:
function prereq(code) {
if (code.style.color != "black") {
code.style.color = "black";
code.style.fontWeight = "normal";
}
}
And otherwise, if the element is already black, I change the color.
The problem/question is: I have to click the element twice before it changes color.
In other words, its not 'black' initially. The if statement is executed, even though the default color, before it is clicked should be black. How do I get it to recognize that when I first click the element, that it's 'black'?
Is jQuery an option? If it is you could do this:http://jsfiddle.net/CxayY/
$('#CSE1020').on('click', function(){
if($('body').css('color')!='black')
{
$('body').css('color','black');
$('body').css('font-weight','normal');
}
});
Try searching in CSSRules:
function prereq(code) {
var cssRules = window.getMatchedCSSRules(code);
...
}
So, it works when I add the style to the element itself, i.e.
<p id="CSE1020" style="color:black" onclick="prereq(this)">CSE1020</p>

Categories

Resources