override :first-child pseudo class styling using jquery - javascript

I need to override the defined :last-child style defined in my stylesheet using jQuery.
I'm aiming for minimal markup using a combination of css and jQuery where the structure around "container-content" is appended to the div on document-ready.
<div id="title-some-impact"><!--Vertical container title--></div>
<div class="container-content-wrapper">
<div></div>
<div class="container-content"><!--Actual container content-->
<div class="sub-container-content"></div>
</div>
<div style=""></div>
</div>
<div style="clear: both;"></div>
</div>
I'm using the first and last div in container-content-wrapper to add rounded corners using css, like so:
.container-content-wrapper>div:first-child { /* rounded corners top */
width: 930px;
height: 16px;
background: url(../Images/top-rounded-corners.png) top no-repeat;
}
.container-content-wrapper>div:last-child { /* rounded corners bottom */
width: 930px;
height: 33px;
background: url(../Images/bottom-rounded-corners.png) top no-repeat;
}
In some cases I need to change the bottom background image using jQuery / JavaScript have failed miserably so far.
I've tried using:
$('.container-content-wrapper>div:first-child').css('background', 'some other link');
Also, adding another class that points to another image does not work.
How can I override the defined :last-child style defined in the stylesheet using jQuery?

$('.container-content-wrapper>div:first-child').css('background', 'some other link');
That selector is fine with your markup. It will select that first div which is a direct ascendant from .container-content-wrapper. So that is not your problem.
CSS selectors have no reference to jQuery selectors, so you cannot "overwrite" them. It looks like your some other link is wrong here.

Actually I initially made a mistake in targeting the div whose style needs to be replaced. It was just a matter of making the correct selection.
For reference, I have solved it by using:
$('.container-content-wrapper:has(.sub-container-content)')
.addClass('container-content-wrapper-for-sub');
where container-content-wrapper-for-sub has this style and is defined below .container-content-wrapper>div:last-child
.container-content-wrapper-for-sub>div:last-child {
/* rounded corners bottom for subsection */
background: url(../Images/bottom-rounded-corners-extra-gray.png);
}

Related

How to use the pseudo selectors in Inline Css in material UI? [duplicate]

I have a case where I must write inline CSS code, and I want to apply a hover style on an anchor.
How can I use a:hover in inline CSS inside the HTML style attribute?
E.g., you can't reliably use CSS classes in HTML emails.
Short answer: you can't.
Long answer: you shouldn't.
Give it a class name or an id and use stylesheets to apply the style.
:hover is a pseudo-selector and, for CSS, only has meaning within the style sheet. There isn't any inline-style equivalent (as it isn't defining the selection criteria).
Response to the OP's comments:
See Totally Pwn CSS with Javascript for a good script on adding CSS rules dynamically. Also see Change style sheet for some of the theory on the subject.
Also, don't forget, you can add links to external stylesheets if that's an option. For example,
<script type="text/javascript">
var link = document.createElement("link");
link.setAttribute("rel","stylesheet");
link.setAttribute("href","http://wherever.com/yourstylesheet.css");
var head = document.getElementsByTagName("head")[0];
head.appendChild(link);
</script>
Caution: the above assumes there is a head section.
You can get the same effect by changing your styles with JavaScript in the onMouseOver and onMouseOut parameters, although it's extremely inefficient if you need to change more than one element:
<a href="abc.html"
onMouseOver="this.style.color='#0F0'"
onMouseOut="this.style.color='#00F'" >Text</a>
Also, I can't remember for sure if this works in this context. You may have to switch it with document.getElementById('idForLink').
You could do it at some point in the past. But now (according to the latest revision of the same standard, which is Candidate Recommendation) you can't
.
You can't do exactly what you're describing, since a:hover is part of the selector, not the CSS rules. A stylesheet has two components:
selector {rules}
Inline styles only have rules; the selector is implicit to be the current element.
The selector is an expressive language that describes a set of criteria to match elements in an XML-like document.
However, you can get close, because a style set can technically go almost anywhere:
<html>
<style>
#uniqueid:hover {do:something;}
</style>
<a id="uniqueid">hello</a>
</html>
If you actually require inline code, this is possible to do. I needed it for some hover buttons, and the method is this:
.hover-item {
background-color: #FFF;
}
.hover-item:hover {
background-color: inherit;
}
<a style="background-color: red;">
<div class="hover-item">
Content
</div>
</a
In this case, the inline code: "background-color: red;" is the switch colour on hover. Use the colour you need and then this solution works. I realise this may not be the perfect solution in terms of compatibility, however this works if it is absolutely needed.
While it appears to be impossible to define a hover-rule inline, you can define the value of styles inline using a CSS variable:
:hover {
color: var(--hover-color);
}
<a style="--hover-color: green">
Library
</a>
Consider using an attribute or a class in addition to the selector (e.g., [hover-color]:hover) to allow coexistence with other low specificity hover color changing rules (from, e.g., a CSS reset or some elements using the default style).
Using JavaScript:
a) Adding inline style
document.head.insertAdjacentHTML('beforeend', '<style>#mydiv:hover{color:red;}</style>');
b) or a bit harder method - adding "mouseover"
document.getElementById("mydiv").onmouseover= function(e){this.className += ' my-special-class'; };
document.getElementById("mydiv").onmouseleave= function(e){this.className = this.className.replace('my-special-class',''); };
Note: multi-word styles (i.e.font-size) in JavaScript are written together:
element.style.fontSize="12px"
This is the best code example:
<a
style="color:blue;text-decoration: underline;background: white;"
href="http://aashwin.com/index.php/education/library/"
onmouseover="this.style.color='#0F0'"
onmouseout="this.style.color='#00F'">
Library
</a>
Moderator Suggestion: Keep your separation of concerns.
HTML
<a
style="color:blue;text-decoration: underline;background: white;"
href="http://aashwin.com/index.php/education/library/"
class="lib-link">
Library
</a>
JS
const libLink = document.getElementsByClassName("lib-link")[0];
// The array 0 assumes there is only one of these links,
// you would have to loop or use event delegation for multiples
// but we won't go into that here
libLink.onmouseover = function () {
this.style.color='#0F0'
}
libLink.onmouseout = function () {
this.style.color='#00F'
}
Inline pseudoclass declarations aren't supported in the current iteration of CSS (though, from what I understand, it may come in a future version).
For now, your best bet is probably to just define a style block directly above the link you want to style:
<style type="text/css">
.myLinkClass:hover {text-decoration:underline;}
</style>
Foo!
As pointed out, you cannot set arbitrary inline styles for hover, but you can change the style of the hover cursor in CSS using the following in the appropriate tag:
style="cursor: pointer;"
<style>a:hover { }</style>
Go Home
Hover is a pseudo class, and thus cannot be applied with a style attribute. It is part of the selector.
You can do this. But not in inline styles. You can use onmouseover and onmouseout events:
<div style="background: #333; padding: 10px; cursor: pointer"
onmouseover="this.style.backgroundColor='#555';" onmouseout="this.style.backgroundColor='#333';">
Hover on me!
</div>
According to your comments, you're sending a JavaScript file anyway. Do the rollover in JavaScript. jQuery's $.hover() method makes it easy, as does every other JavaScript wrapper. It's not too hard in straight JavaScript either.
There is no way to do this. Your options are to use a JavaScript or a CSS block.
Maybe there is some JavaScript library that will convert a proprietary style attribute to a style block. But then the code will not be standard-compliant.
You can write code in various type.
First I can write this
HTML
<a href="https://www.google.com/" onMouseOver="this.style.color='red'"
onMouseOut="this.style.color='blue'" class="one">Hello siraj</a>
CSS
.one {
text-decoration: none;
}
You can try another way:
HTML
Hello siraj
CSS
.one {
text-decoration: none;
}
.one:hover {
color: blue;
}
.one:active {
color: red;
}
You can also try hover in jQuery:
JavaScript
$(document).ready(function() {
$("p").hover(function() {
$(this).css("background-color", "yellow");
}, function() {
$(this).css("background-color", "pink");
});
});
HTML
<p>Hover the mouse pointer over this paragraph.</p>
In this code you have three functions in jQuery. First you ready a function which is the basic of a function of jQuery. Then secondly, you have a hover function in this function. When you hover a pointer to the text, the color will be changed and then next when you release the pointer to the text, it will be the different color, and this is the third function.
I just figured out a different solution.
My issue: I have an <a> tag around some slides/main content viewer as well as <a> tags in the footer. I want them to go to the same place in IE, so the whole paragraph would be underlined onHover, even though they're not links: the slide as a whole is a link. IE doesn't know the difference. I also have some actual links in my footer that do need the underline and color change onHover. I thought I would have to put styles inline with the footer tags to make the color change, but advice from above suggests that this is impossible.
Solution: I gave the footer links two different classes, and my problem was solved. I was able to have the onHover color change in one class, have the slides onHover have no color change/underline, and still able to have the external HREFS in the footer and the slides at the same time!
It's not exactly inline CSS, but it is inline.
<a href="abc.html" onMouseOver="this.style.color='#0F0'"
onMouseOut="this.style.color='#00F'">Text</a>
I agree with shadow. You could use the onmouseover and onmouseout event to change the CSS via JavaScript.
And don't say people need to have JavaScript activated. It's only a style issue, so it doesn't matter if there are some visitors without JavaScript ;)
Although most of Web 2.0 works with JavaScript. See Facebook for example (lots of JavaScript) or Myspace.
So this isn't quite what the user was looking for, but I found this question searching for an answer and came up with something sort of related. I had a bunch of repeating elements that needed a new color/hover for a tab within them. I use handlebars, which is key to my solution, but other templateing languages may also work.
I defined some colors and passed them into the handlebars template for each element. At the top of the template I defined a style tag, and put in my custom class and hover color.
<style type="text/css">
.{{chart.type}}-tab-hover:hover {
background-color: {{chart.chartPrimaryHighlight}} !important;
}
</style>
Then I used the style in the template:
<span class="financial-aid-details-header-text {{chart.type}}-tab-hover">
Payouts
</span>
You may not need the !important
While the "you shouldn't" context may apply there may be cases were you still want to achieve this. My use case was to dynamic set a hover color depending on some data value to achieve that with only CSS you can benefit from specificity.
Approach CSS only
CSS
/* Set your parent color for the inherit property */
.sidebar {
color: green;
}
/* Make sure your target element "inherit" parent color on :hover and default */
.list-item a {
color: inherit
}
.list-item a:hover {
color: inherit
}
/* Create a class to allows to get hover color from inline style */
.dynamic-hover-color:not(:hover) {
color: inherit !important;
}
Then your markup will be somewhat like:
Markup
<nav class="sidebar">
<ul>
<li class="list-item">
<a
href="/foo"
class="dynamic-hover-color"
style="color: #{{category.color}};"
>
Category
</a>
</li>
</ul>
</nav>
I'm doing this example using handlebars but the idea is that you take whatever is convenient for your use case to set the inline style (even if it is writing manually the color on hover you want)
You can just use an inline stylesheet statement like this:
<style>#T1:hover{color:red}</style><span id=T1>Your Text Here</span>
You can use the pseudo-class a:hover in external style sheets only. Therefore I recommend using an external style sheet. The code is:
a:hover {color:#FF00FF;} /* Mouse-over link */
You can do id by adding a class, but never inline.
<style>.hover_pointer{cursor:pointer;}</style>
<div class="hover_pointer" style="font:bold 12pt Verdana;">Hello World</div>
It is two lines, but you can reuse the class everywhere.
My problem was that I'm building a website which uses a lot of image-icons that have to be swapped by a different image on hover (e.g. blue-ish images turn red-ish on hover).
I produced the following solution for this:
.container div {
width: 100px;
height: 100px;
background-size: 100px 100px;
}
.container:hover .withoutHover {
display: none;
}
.container .withHover {
display: none;
}
.container:hover .withHover {
display: block;
}
<p>Hover the image to see it switch with the other. Note that I deliberately used inline CSS because I decided it was the easiest and clearest solution for my problem that uses more of these image pairs (with different URL's).
</p>
<div class=container>
<div class=withHover style="background-image: url('https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQrqRsWFJ3492s0t0NmPEcpTQYTqNnH188R606cLOHm8H2pUGlH')"></div>
<div class=withoutHover style="background-image: url('http://i.telegraph.co.uk/multimedia/archive/03523/Cat-Photo-Bombs-fa_3523609b.jpg')"></div>
</div>
I introduced a container containing the pair of images. The first is visible and the other is hidden (display:none). When hovering the container, the first becomes hidden (display:none) and the second shows up again (display:block).

Is a sticky header possible in AMP?

So far I haven't found a solid way to create a sticky header on AMP pages. I know there are CSS workaround/hacks, but nothing I can use in a production environment. A simple "position:fixed;" unfortunately won't work in my case.
Out of all the components, I thought there would be one that toggles a body class on scroll, but I haven't found anything yet. Also don't think "amp-position-observer" will be of any use.
Am I missing something? Ideally I'd like to be able to toggle an element's class name after a scroll of X amount of pixels. Is this possible in AMP?
Toggling an element's classname after a scroll of X amount of pixels is currently not supported as amp-position-observer does not allow changing amp-state.
You can combine amp-position-observer to change parts of the header using amp-animation. However, it's application is limited as the supported CSS properties are limited. Nevertheless, with a little bit of creativity this approach can be quite flexible. One possible pattern is to duplicate elements in your header which are then shown/hidden based on your scrolling position.
Here is a sample highlighting the header based on the currently focused section.
I built a working solution of a sticky header within an amp-list. The pitfall is that amp elements add display: block and position: absolute on many elements.
To use position: sticky you need to use display: inline and position: relative on all subelements on your header. Make sure these are actually applied and not overwritten, use id to get a higher specificity over the amp css classes.
Here's an example using an amp list
css:
All divs need display: inline
The amp-list gets an id (not class) to apply css to itself and the generated child div
Divs can be nested as long as they use display: inline
.sticky {
position: sticky;
z-index: 1;
display: inline-block;
box-sizing: border-box;
width: 100%;
background-color:white;
top: 40px;
}
.inline {
display: inline;
}
#list-wrapper, #list-wrapper>div {
display: inline;
position: relative;
}
<div>
<amp-list [src]="..." items="." single-item layout="flex-item" id="list-wrapper">
<template type="amp-mustache">
<div class="inline">
<span class="sticky">
<span>Sticky header</span>
</span>
</div>
</template>
</amp-list>
<div>Your content</div>
<div>

How to check if 2 elements displayed on the same row?

Assuming I have 2 elements on a responsive design like this:
<div id="container">
<div class="first"></div>
<div class="second"></div>
</div>
both of them with style contains:
width: auto;
display: inline-block;
float: left;
And because I'm expecting different screen sizes to view page, so, according to screen size, sometimes they will be rendered/displayed on the same row, and sometimes they will not!, the second DIV will be moved to a separate row.
So, I'm wondering, how can I check if they are on the same line with JavaScript?
Thank you
"on the same line" would require inline elements or floating block elements of the exact same height. DIVs are block elements by default. So either use <span> tags instead of <div>, or add display: inline-block;to the CSS rule of those DIVs
ADDITION after EDIT OF QUESTION:
width: auto for a <div> means 100% of the parent element (in this case full width). As I wrote: If you have blocks, use display: inline-block; in their CSS. If you want them to have the same height, put them into a common container DIV (which you already have) and apply the following CSS:
#container {
display: table;
}
.first, .second {
display: table-cell;
width: 50%;
}
Aha (edited question), Javascript: Well, read out the DIV widths, add them and compare the result to the (read-out) container width.
You can use the element bounding boxes and check for overlap:
var rect1 = $('.first')[0].getBoundingClientRect();
var rect2 = $('.second')[0].getBoundingClientRect();
var overlaps = rect1.top <= rect2.bottom && rect2.top <= rect1.bottom;
This checks for any overlap which will probably be sufficient for your use. I used jQuery to get the elements but you can use pure js in the same way, it would just be a bit more verbose.
There is no concept of line on a page. You can check the x and y position of any element in the window and then decide if that meets whatever criteria you have for "on the same line".
By default, a div is the full width of a window so the two divs inside your container in this HTML:
<div id="container">
<div class="first"></div>
<div class="second"></div>
</div>
will be one above the other unless there is some other CSS you have not disclosed that controls the layout to allow them to be in the same row. If they are indeed width: auto and don't have any other layout rules affecting this, then they will each be full width and thus first will be above second in the layout stream. They would never be "on the same line" by any typical definition of that phrase.
Feel free to try it out here: https://jsfiddle.net/jfriend00/y0k7hLr8/ by resizing the right pane to any width you want. In all cases, the first will stay on top of the second.
If, on the other hand, you allow the div elements to have a different type of layout such as let them be display: inline-block and define a width for them, then the layout engine will fit as many on a given row as possible like here: https://jsfiddle.net/jfriend00/229rs97p/
Something tells me display: flex might help you in this. Read https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for more info.

trying to use jQuery switchClass to create a reveal animation

I'm trying to get an element to change its class to one with a different height attribute to make a reveal effect. I'm just getting an error which says uncaught type error undefined is not a function.
html -
<div id="rollup" class="header-container">
<header class="wrapper clearfix">
<h1 class="title"></h1>
<nav>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</nav>
</header>
<p class="btnRetract">
see more
</p><!--end div retract -->
</div><!--end div rollup-->
Javascript -
$(".btnRetract").on("click", function() {
var $content = $("#rollup");
switchClasses($content);
     
return false;
 
function switchClasses($content){
if($content.hasClass("header-container")){ 
$content.switchClass("header-container", "header-container-retracted");
}
else {
$content.switchClass("header-container-retracted", "header-container");
}
}
CSS -
.header-container {
border-bottom: 20px solid #e44d26;
height: 90vh;
position:relative;
}
.header-container-retracted {
border-bottom: 20px solid #e44d26;
height: 20vh;
position:relative;
}
That's because switchClass is not a function defined by the jQuery plugin. It is actually part of the jQuery UI framework. However, if you need to "switch" classes using the jQuery plugin you can use either toggleClass, removeClass and addClass. Furthermore, you can even use animate to customise the transitions between property values
You dont need a switchClass function (doesnt exist anyway and is causing your error)
You can use answer from squint or.if you dont want to check.for the existence of one of the classes you can do this all in one line:
$content.removeClass('header-container').addClas('header-container-retracted');
As others have pointed out, it would be easier to use the jQuery toggle method, but there are other issues as well with your Javascript and CSS. Here's a working demo that you can use as an example.
Demo
Javascript:
$(".btnRetract").on("click", function() {
$("#rollup").toggleClass('header-container-retracted');
});
That's all you need for the click handler if you're using the built in toggleClass method. It accepts one string as an argument, which is the name of the class that you want to toggle. You can also have a comma separated list of two class names, wherein it will toggle between the two classes, but in this case, you don't need to swap the classes. You simply want to add or remove your .header-container-retracted class, because your .header-container class has all of your base styles in it. The .header-container-retracted class only has to contain the properties you want to override in the base styles and as long as it is AFTER your base .header-container class in your stylesheet, the normal cascading behavior of CSS will ensure that its properties will override the base properties.
CSS:
.header-container {
position: relative;
border-bottom: 1.5em solid #e44d26;
height: 85vh;
overflow: hidden;
margin: 0;
padding: 0;
-webkit-transition: height 1s ease;
transition: height 1s ease;
background-color: white;
padding: 1em;
}
.header-container-retracted {
height: 3.5em;
}
So, in your CSS, you don't need to repeat any of your styles in the .header-container-retracted. Note also, that I added overflow: hidden to the base styles. Without this, your content "inside" the header-container element would just spill out and be visible when the header-container was "retracted". Also, I add some transitions to give the opening and closing a nice smooth animation. The transitions will not be supported in IE8 or IE9, but they will not prevent the opening/closing of the element. As #Leo pointed out, if the animation is important to you in IE8/IE9 browsers, you can use jQuery's animate method to handle the transitions instead.
Finally, you'll note in the demo that I set your .btnRetractelement absolute positioning. Because you're using relative heights, you need to ensure that your toggle button is always visible. On a very small viewport, 20vh would be so small that it would obscure the button and make it impossible to expand the header-container.

Can I make a link fill its parent without using display:block or display:inline-block?

See this JSFiddle
I want to make the .newslink links all the way to the borders of the .content divs.
I have a slideshow of different content that gets messed up either if I set the a tag around the div or if I apply display:block / display:inline-block to the a element.
Right now the links are only around the image and text because of the 15px padding in .content. You can check this by hovering your mouse over the div (near the border) compared to over the image and text area. I want each link to completely fill the surrounding div.
Is it in this case possible to accomplish without setting the a tag around the div or applying display:block / display:inline-block to the a element?
Working Fiddle: http://jsfiddle.net/8tqryvu5/
Firstly, let's get rid of the Table markup as you're not marking up a table.
<div id="tableNews">
<div class="cell2">
<div id="slideshow">
<div class="content">
<a href="#" id="rightLink1" class="newsLink" target="_blank">
<div class="picDiv">
<img id="rightPic1" class="pic2" src="http://static3.businessinsider.com/image/5238c9c5ecad047f12b2751a/internet-famous-grumpy-cat-just-landed-an-endorsement-deal-with-friskies.jpg"/>
</div>
<div class="text">
<h2 id="title1">title 1</h2>
<p id="rightBoxSubText1">asdasd</p>
</div>
</a>
</div>
</div>
</div>
</div>
To achieve the effect you should apply the padding to the anchor link as this wraps both the images and text (essentially forming the border). Here's the part to take note of:
.newsLink {
display: block;
padding: 15px;
}
As it's an inline element you will need to set it to display:block in order to make it wrap the elements inside it. If you correctly apply the style to the surrounding elements then setting it to display:block will not effect the layout.
Hope that helps.
I am not 100% sure that I got right the whole thing but I think you can achieve this by using
.newsLink{position:absolute;top:0;left:0;bottom:0;right:0;background:red}
It will take the wodth of the slideshow, which is the relative element. If you want it to take the size of the .content and not more you will have to add a wrap in display block around you tag
Here is a jsfiddle: http://jsfiddle.net/8c041xy7/5/
You just need to absolute position anchor tag
.newsLink {
display: block;
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
}

Categories