Reputation: 3628
So I got the following problem:
I got an element with this CSS ($(this)
is the cloned object):
clone.css({
'width': $(this).width() + 'px',
'height': $(this).height() + 'px',
'top': $(this).offset().top - $(window).scrollTop() + 'px',
'left': $(this).offset().left + 'px',
'position': 'fixed'
});
On click I add following class:
.dupe{
top:0;
left:0;
width:100%;
height:300px;
border-radius:0;
box-shadow:none;
transition:all .3s ease-in-out;
}
That doesn't work tho, because jQuery overwrites it. I don't want to use !important
.
So is there a way to tell the CSS like "now you're important and now you're not", without using !important
?
Upvotes: 1
Views: 102
Reputation: 4830
Using jQuery.css
sets the style as inline styles on the element. You will need to use !important
to override it from a stylesheet.
One way of handling this would be to use class names for all styles and use classes to toggle the styles.
If that is not an option, you can use jQuery.css
after click to either reset the properties to their initial values (by setting them to ''
) or set them to the values they need to be.
Live example of setting them to ''
:
var clone = $(".target").clone();
clone.css({
'width': '80px',
'height': '20px',
'top': '40px',
'left': '50%',
'position': 'fixed'
});
clone.appendTo(document.body);
console.log("Added styling to clone");
setTimeout(function() {
console.log("Removed styling from clone");
clone.addClass("dupe").css({
'width': '',
'height': '',
'top': '',
'left': '',
'position': ''
});
}, 800);
.target {
border: 1px solid #ddd;
}
.dupe {
color: blue;
}
<div class="target">
Hi there
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You could also remove the style attribute entirely using jQuery.removeAttr
if that is an option too. This will effectively remove inline styling allowing your other styles to kick in. But it will also remove any other inline styles that the elements have.
Live Example of removing the style
attribute entirely:
var clone = $(".target").clone();
clone.css({
'width': '80px',
'height': '20px',
'top': '40px',
'left': '50%',
'position': 'fixed'
});
clone.appendTo(document.body);
console.log("Added styling to clone");
setTimeout(function() {
console.log("Removed styling from clone");
clone.addClass("dupe").removeAttr("style");
}, 800);
.target {
border: 1px solid #ddd;
}
.dupe {
color: blue;
}
<div class="target">
Hi there
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 3
Reputation: 81
jQuery adds it's styles as inline which always overwrite regular css without the !important tag. The best I can think of is making a function to apply the dupe class as inline styles also.
Something like:
object.css({
'top':'0',
'left':'0',
'width':'100%',
'height':'300px',
'border-radius':'0',
'box-shadow':'none',
'transition':'all .3s ease-in-out'
});
Upvotes: 1