How to get CSS of a clicked div using jQuery? - javascript

Can anybody know how to get border-color of a div using jQuery.
$("#divcolor").click(function (){
alert("dsf");
var divcolor = $(this).css("border-color");
alert(divcolor);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="divcolor" style="border:#333333 solid 1px;" >
This is the target
</div>
In divcolor variable I am not getting anything.

Using the CSS jQuery function like you did:
http://docs.jquery.com/CSS/css#name
But read this paragraph:
Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.

Your mistake is elsewhere. That code works on Chrome and IE.

border-color isn't working for me either (on Firefox), but this works:
$(this).css("border-top-color")
http://jsbin.com/ezefu

I always consider it better practice to work with CSS classes instead of CSS direct. Then you could have something like:
$(this).hasClass("MyClassWithTheBorderColorStyleInIt");

You can write like this
$("#divcolor").click(function() {
var divcolor = $(this).css("border");
divcolor = divcolor.substring((divcolor.indexOf(' ') + 1), divcolor.length);
divcolor = divcolor.substring((divcolor.indexOf(' ') + 1), divcolor.length);
alert(divcolor);
});

$("#divcolor").click(function (){
var divcolor = $(this).css("borderColor");
alert(divcolor);
});

Try this one:
$("#divcolor").click(function (){
alert("dsf");
var divcolor = $(this).css("border-color");
alert(divcolor);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="divcolor" style="border:1px solid; border-color:#333333;" >
This is the target
</div>

Related

Select and Replace an embedded style with jQuery

Is it possible to select and replace an embedded styles background path with jQuery? I'm having trouble getting this to work.
<script>
$(document).ready(function($) {
function myReplaceFunc() {
var $str = $('style');
$str.replace('wcsstore', 'mytest');
}
myReplaceFunc();
});
</script>
<style>
#test{
background: url("/wcsstore/***/en_GB/images/suppliershop/ecomheader.jpg");
}
</style>
<section id="test">Test 1</section>
<section id="test2">Test 2</section>
Any help much appreciated.
Aside from the issue with calling replace() on a jQuery object, your approach to this is flawed. While it's possible to amend the content of <style> tags with JS, it's very far from the best solution.
Instead, you should set the background-image on the element directly using the css() method. You can provide a function to this method which receives the current value as an argument. You can then call replace() on that - as you currently are - to update the value. Try this:
$(document).ready(function($) {
function myReplaceFunc() {
$('#test').css('background-image', function(i, bg) {
return bg.replace('wcsstore', 'mytest');
});
}
myReplaceFunc();
});
#test {
background: url("/wcsstore/***/en_GB/images/suppliershop/ecomheader.jpg");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="test">Test 1</section>
<section id="test2">Test 2</section>
Use .text() chained to jQuery() to get, set the .textContent of the element
$str.text($str.text().replace('wcsstore', 'mytest'));
1- get the background image url from css applied
var bg = $('#test').css('background-image');
bg = bg.replace('url(','').replace(')','').replace(/\"/gi, "");
2- change the url
var new_url = bg.replace('wcsstore','mytest');
3- replace the url
$('#test').css('background-image', 'url(' + new_url + ')');

How can I make a javascript that sets the background color of an element to the innerhtml color code?

As I'm making a style template for a website, I'd like to make span elements that from example blocks with a background color. Example:
<span class='colblock'>#FF0000</span>
should result in a block with color code #FF0000 (Red) as background color.
Currently, the following css and JS code is being used (relevant bits)CSS
<style>
span.colblock{
margin:8px;
padding:8px;
display:block;
border:1px solid black;
border-radius:2px;
width:66px;
}
</style>
Javascript (On page bottom, just before body)
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
$("colblock").each(function() {
var ccode = $(this).html();
$(this).css("background-color", ccode);
});
</script>
IMO, this is supposed to work, but it does not. Can someone elighten me?
While selecting element by class use . operator. You have error here:
$(".colblock").each(function() {
^ //missed '.' dot
Use following:
$(".colblock").each(function() {
var ccode = $(this).html();
$(this).css("background-color", ccode);
});
In css also you having typo:
<span.colblock{
^ //===> should be removed
See working Example
Use $(this).text() instead of $(this).html()
$(".colblock").each(function() {
var ccode = $(this).text();
$(this).css("background-color", ccode);
});
And in your css <span.colblock should be like this: span.colblock
To select a class, you should use $(".ClassName"), here it will be $(".colblock").
$("colblock") will select elements with tag name "colblock".
Your jquery link seems dead.
src="//code.jquery.com/jquery-migrate-1.2.1.min.js"
This one works as I tested:
src="http://code.jquery.com/jquery-1.2.1.min.js"
Not using JQuery
var the_Span = document.getElementById("colblock");
var span_Text = the_Span.innerText;
the_Span.style.backgroundColor = span_Text;

change background color of div with jquery that has an !important tag

Using a plugin that calls a .jsp that uses its own stylesheet hosted externally (it's a yelp embed - trying to manipulate the look of it). The one element I'm trying to change has an !important tag on it, and I can't seem to change it...
I tried
<script type="text/javascript">
$('.elementToChange').css({'background-color':'black'});​
</script>
to no avail. Ideas?
It looks like in more up-to-date versions of jQuery (at least 1.7.2 and higher) you can simply set the css:
$('#elementToChange').css('background-color', 'blue');
See http://jsfiddle.net/HmXXc/185/
In older versions of jQuery and Zepto you had to clear the css first:
// Clear the !important css
$('#elementToChange').css('background-color', '');
And then reset it using:
$('#elementToChange').css('background-color', 'blue');
Or in a one-liner:
$('#elementToChange')
.css('background-color', '')
.css('background-color', 'blue');
See http://jsfiddle.net/HmXXc/186/.
Original answer:
Note: this may be a bad idea, as it will remove any other inline styles
I would edit the style attribute directly
$('.elementToChange').attr('style', 'background-color: blue !important');
http://jsfiddle.net/RichardTowers/3wemT/1/
Here is your solution:
http://jsfiddle.net/irpm/bdhpp/2/
The idea is to add the class:
$('.elementToChange').addClass('blackBg');
You can manipulate !important css by using following steps, either you can use inline-css or Internal css or you can load your own external css after the order of that preloaded css, it will help you to override that css with your custom one.
<html>
<head>
<!--
//First Solution
//PreloaderCSS
//YourCustomCSS
//Second Solution
Internal CSS -->
</head>
<body>
<!--
Third solution
//Inline CSS
->
</body>
</html>
You can use the following function:
function replaceBGColorImportant(element,newColor){
var styles = element.getAttribute('style');
styles = styles?styles.split(';'):[];
var newStyles = [];
styles.map(function(x){
if (x.split(':')[0] != "background-color")
newStyles.push(x);
});
newStyles.push('background-color:#'+newColor+' !important');
element.setAttribute('style',newStyles.join(';'));
}
Execute as follows:
replaceBGColorImportant(document.body,'#009922');
Via regular expression:
https://jsfiddle.net/7jj7gq3y/2/
HTML:
<div class="elementToChange" style=" background-color: yellow !important; width: 100px; height: 100px;"></div>
JavaScript:
var setImportantStyle = function(element, attributeName, value) {
var style = element.attr('style');
if (style === undefined) return;
var re = new RegExp(attributeName + ": .* !important;", "g");
style = style.replace(re, "");
element.css('cssText', attributeName + ': ' + value + ' !important;' + style);
}
setImportantStyle($('.elementToChange'), 'background-color', 'red');

jquery get styles from an id

does anyone know how can i get all styles applied to an id using jquery (so i can reuse it later in another tag)? something like
css:
div#myid{
width:100px;
height:100px;}
so i can later do something like:
for (var parts in $('#myid').css())
alert ('all parts of the style' + parts);
$('#myid').attr('class') returns a string of the classes.
You should be able to figure it out from here.
var classes = $('#myid').attr('class').split(' ');
for(var c in classes)
{
alert(classes[c]);
}
It is not jquery but works well:
var style = window.getComputedStyle(document.getElementById('myid'), null);
alert(style.color);
You can replace document.getElementById('myid') by $('#myid').get(0) if you really want to use jquery here.
This works either for a style given by CSS or directly applied on the element with the style attribute.
Not sure.. I had tried attr('class') before and it returned empty. trying now again produces the same result (nearly). i suppose attr('class') in jquery isnt exactly the same as styles defined via id. try running this, let me know if you get different results please:
<html>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function (){
alert($('#myid').attr('class')); // returns 'empty'
var classes = $('#myid').attr('class').split(' ');
for(var c in classes){
alert(c); // returns 0
}
});
</script>
<style>
#myid {
width:100px;
height:100px;
background:red;
}
</style>
<body>
<div id="myid"></div>
</body>
</html>

how to make div click-able?

<div><span>shanghai</span><span>male</span></div>
For div like above,when mouse on,it should become cursor:pointer,and when clicked,fire a
javascript function,how to do that job?
EDIT: and how to change the background color of div when mouse is on?
EDIT AGAIN:how to make the first span's width=120px?Seems not working in firefox
Give it an ID like "something", then:
var something = document.getElementById('something');
something.style.cursor = 'pointer';
something.onclick = function() {
// do something...
};
Changing the background color (as per your updated question):
something.onmouseover = function() {
this.style.backgroundColor = 'red';
};
something.onmouseout = function() {
this.style.backgroundColor = '';
};
<div style="cursor: pointer;" onclick="theFunction()">
is the simplest thing that works.
Of course in the final solution you should separate the markup from styling (css) and behavior (javascript) - read on it on a list apart for good practices on not just solving this particular problem but in markup design in general.
The simplest of them all:
<div onclick="location.href='where.you.want.to.go'" style="cursor:pointer"></div>
I suggest to use jQuery:
$('#mydiv')
.css('cursor', 'pointer')
.click(
function(){
alert('Click event is fired');
}
)
.hover(
function(){
$(this).css('background', '#ff00ff');
},
function(){
$(this).css('background', '');
}
);
I suggest to use a CSS class called clickbox and activate it with jQuery:
$(".clickbox").click(function(){
window.location=$(this).find("a").attr("href");
return false;
});
Now the only thing you have to do is mark your div as clickable and provide a link:
<div id="logo" class="clickbox"></div>
Plus a CSS style to change the mouse cursor:
.clickbox {
cursor: pointer;
}
Easy, isn't it?
add the onclick attribute
<div onclick="myFunction( event );"><span>shanghai</span><span>male</span></div>
To get the cursor to change use css's cursor rule.
div[onclick] {
cursor: pointer;
}
The selector uses an attribute selector which does not work in some versions of IE. If you want to support those versions, add a class to your div.
As you updated your question, here's an obtrustive example:
window.onload = function()
{
var div = document.getElementById("mydiv");
div.style.cursor = 'pointer';
div.onmouseover = function()
{
div.style.background = "#ff00ff";
};
}
<div style="cursor: pointer;" onclick="theFunction()" onmouseover="this.style.background='red'" onmouseout="this.style.background=''" ><span>shanghai</span><span>male</span></div>
This will change the background color as well
If this div is a function I suggest use cursor:pointer in your style like style="cursor:pointer" and can use onclick function.
like this
<div onclick="myfunction()" style="cursor:pointer"></div>
but I suggest you use a JS framework like jquery or extjs

Categories