Dynamic picture depends on attribute - javascript

My target is to have a list of file names, and near every item a picture of that file extension will appear next to it.
there is a nice way to do that:
p[icon^=".gif"]
{
background: url(images/gif.png) no-repeat center left)
}
this checks if the icon attribute of the 'p' element ends with .gif. if it does,
it applies the given style to that element.
but instead of define every file type, i want it to be generic since i have a folder with icons in this format: {file-extansion}.png
in case there is no matching file with the given extansion or there is no file extansion, there will be a default path of "default.png".
There is an option to do that or part of that? if no, what way you advise me doing that?
By the way I am not a css/javascript expert so please given enough details so I can understand your answers.

You can use jQuery library for this:
HTML
<p data-ext=".gif">Text</p>
<p data-ext=".png">Text</p>
<p data-ext=".jpg">Text</p>
CSS
p {
background-repeat: no-repeat;
background-position: 0 50%;
}
JavaScript
$("p[data-ext]").each(function() {
var ext = $(this).data("ext").substring(1);
$(this).css("background-image", "url(images/" + ext + ".png)");
});
It works so that you add data-ext attribute to each p (or whatever) tag. jQuery selects all p tags which have data-ext attribute, then gets attribute value, and changes background-image of each element.
DEMO: http://jsfiddle.net/AEsx4/

Using pure CSS, you can't dynamically reference attributes in the URL, but you can make them content. Here are some lame workarounds using pure CSS and finally a wishful thinking approach :(
Use a class
<div class="jpg">
</div>
/* css */
.jpg {
background: url("/img/jpg.jpg");
}
This works great, but you need one class per extension.
Use an attribute selector
<div data-ext="jpg"></div>
div[data-ext=jpg] {
background: url(/img/jpg.jpg);
}
For more on this approach see:
http://css-tricks.com/attribute-selectors/
I used data-ext, because in HTML you're not really supposed to add random tags, so the HTML creators gave us data-* which is valid HTML5 and we can do whatever want with it. Either way, you need to create a new CSS selector for every extension. Not good.
Closest you can get with pure css
<div data-ext="jpg"></div>
div:after {
content: attr(data-ext);
}
You will see the name of the extension next to the div. This almost works, but it's not quite good enough.
More about CSS Functions: http://www.suburban-glory.com/blog?page=130
What you actually want
<div data-ext="jpg"></div>
div:after {
content: url("/img/jpg." attr(data-ext));
}
Sadly this doesn't appear to work at the moment, but boy would it be awesome.

Related

How can I hide browser broken default image added on empty src <img /> with css? [duplicate]

I'd like to give broken/errored images some extra CSS:
img:error {
max-width: 20px;
max-height: 20px;
}
but that doesn't work. Is there a way with pure CSS to do this? Is there an img pseudo selector for this? Or even better: a dirty hack that works?
I've looked around, but nobody seems to be wondering =)
(Yes, I know JS can do it and I know how; no need to mention it.)
There is no way in CSS specs or drafts, but Firefox has a proprietary selector (pseudo-class) :-moz-broken. Its documentation is very concise and it says “intended for use mainly by theme developers”, but it can be used e.g. as follows:
:-moz-broken { outline: solid red }
:-moz-broken:after { content: " (broken image)" }
Although the documentation says that it “matches elements representing broken image links”, it actually matches broken images (an img element where the src attribute does not refer to an image), whether they are links or not. Presumably, “links” really means “references” here.
CSS 2.1 says: “This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.” But Selectors Level 3 (CSS3 Selectors) just says about them: “They are explained in CSS 2.1.” In practice, browsers handle them differently. Oddly enough, Firefox supports :-moz-broken:after but ignores :-moz-broken:before. It does not support either of these pseudo-elements for normal images, but img:after, too, is supported for a broken image (i.e., the specified content appears after the alt attribute value).
For this, you should use the alt attribute, wich shows up if link is broken and you can as well style background of image :
example:
img {
display:inline-block;
vertical-align:top;
min-height:50px;
min-width:300px;
line-height:50px;
text-align:center;
background:
linear-gradient(to bottom,
blue,
orange,
green);
font-size:2em;
box-shadow:inset 0 0 0 3px;
}
These style will be hidden when image is shown.
http://codepen.io/anon/pen/Kxipq
As you can see, we do not check for broken links, but offer alternative , usefull for blind people , searchengines, whatever , and some extra styles finishes it :)
some extra Image alt attribute best practices
<img src="not_found_image.png" onerror='this.style.display = "none"' />
from:
https://www.geeksforgeeks.org/how-to-hide-image-not-found-icon-when-source-image-is-not-found/
NO there is no :error pseudo class. This is a good site for a comprehensive list of what is available:
http://reference.sitepoint.com/css/css3psuedoclasses
July, 2015 EDIT/ADDITION:
(Thank you Rudie)
https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes
No. There is nothing in CSS selectors level 2.1 or level 3 that allows targeting an image like that.
This is close:
<style>
img[data-broken="true"] {
visibility: hidden;
}
</style>
<img src="none.webp" onerror="this.setAttribute('data-broken', 'true')">
Strictly speaking, it sill uses JavaScript. But the JS is self contained in the image HTML code.

Can I use JQuery with inline html? If so how?

I learned html and css a week ago. I completed my first project only to find that a div tag I used was not resizing to mobile formats. I have done some research and it seems the answer may reside with JQuery or .JS. I am working within a contained environment, Wordpress.com, and I don't know Java Script yet, but I am familiar with if then statements from studying logic for years.
So I effectively have two problems:
Can I use JQuery with inline html: no css?
How do I do it?
I know I am way off here. I am in the process of going through a .JS tutorial on codeacademy, but I am not finished.
Just thought I would try for advice here. I may not even be in the ballpark!
Here is my div tag and here is what I attempted:
<div style="width:950px;height:5px;background-color:#FFFFFF;"></div>
$(window).resize(function() {
if ($(this).width() < 951) {
$('.divIWantedToHide').hide(<div style="width:950px;height:5px;background-color:#FFFFFF;"></div>);
} else {
$('.divIWantedToHide').show(<div style="width:450px;height:5px;background-color:#FFFFFF;"></div>);
}
});
Javascript is kind of over-kill for this kind of thing.
I would suggest using CSS media queries.
Paste this in and it should work just fine :)
<style>
#YourDiv{
height:5px;
background-color:#FFFFFF;
}
#media only screen and (min-width:951px){
#YourDiv{width:950px;}
}
#media only screen and (max-width:950px){
#YourDiv{width:450px;}
}
</style>
<div id="YourDiv"></div>
Instead of having your style defined in the div tag, your div now has a unique name (an id) that can be styled separately. This is incredibly useful, and most would argue necessary, once you start building more complicated pages. The #media tags do basically the same thing as your if statements, where min-width:951px will set the style when your window is AT LEAST 951px and max-width:950px sets the style when your window is AT MOST 950px. The rest of the styles that don't change are set above ONE time because they are the same regardless of window size.
And now, just for fun I'll show you how to do it in pure Javascript as well:
http://jsfiddle.net/AfKU9/1/ (test it out by changing the preview window size)
<script>
var myDiv = document.getElementById("myDiv");
window.onresize = function(){
var w = window.innerWidth;
if (w > 600){
myDiv.setAttribute("style",'position:absolute;height:50px;background-color:#CCC;width:400px;' )
}
else{
myDiv.setAttribute("style", 'position:absolute;height:50px;background-color:#333;width:100px;' )
}
}
</script>
$('.divIWantedToHide').hide() will hide the div !!
In order to apply css to this div you need to use css:
$('.divIWantedToHide').css('width':'950px','height':'5px','background-color':'#FFFFFF');
If you want to append any div and apply css to it then use append/html
$('.divIWantedToHide').append('<div style="width:950px;height:5px;background-color:#FFFFFF;"></div>');
or
$('.divIWantedToHide').html('<div style="width:950px;height:5px;background-color:#FFFFFF;"></div>');
No, at wordpress.com you won't be able to use inline JavaScript. Not in regular posts using the HTML editor nor using the Custom Design upgrade that only includes a CSS editor.
Maybe you'll benefit from the following:
Preprocessor
WordPress.com has support for CSS preprocessors LESS and Sass (SCSS Syntax). This is an advanced option for users who wish to take advantage of CSS extensions like variables and mixins. See the LESS and Sass websites for more information. You can select which syntax you would prefer to use at the bottom of the Appearance -> Customize -> CSS panel.
If you want to resize or apply another style to some elements adapted to the device screen size, yout can just use the #media css property.
#your_div_id {
width: 950px;
/* ... */
}
#media (max-width: 38em) {
#your_div_id {
display:none;
}
}
You are trying to hide a div with class '.divIWantedToHide'. But your div does not have any class.
So you should add to your div the class:
<div class="divIWantedToHide" style="width:950px;height:5px;background-color:#FFFFFF;"> </div>
And then, you can show and hide it like here:
$(".divIWantedToHide").hide()
$(".divIWantedToHide").show()

How to trigger bootstrap's mouseover effect programmatically

In twitter bootstrap, some elements get "greyed out" when the mouse hovers over them. This is true of buttons and linked list group items. Two examples are here: http://imgur.com/a/ABhkT#0
Can this effect be triggered programmatically? If so, how?
Yes, Using the 'onmouseover' attribute. It is quite similar to the 'onclick', except obviously for hovering instead.
Like the 'onclick', you will have to include a java script function that would change the css style for that element.
Depending on what you are trying to have this effect on, you could either put it right into the tag that is the object, or use <span></span>.
Ex:
<div onmouseover="fade()">
<p>text to fade</p>
</div>
Javascript:
function fade(){
code to change style
}
should be straight forward, this would fade everything inside the div (including the background)
Ok, I figured it out.
If the effect were being caused by a css class, one could simply apply the class to the element, like this:
$('<my_element>').addClass('bootstrapMouseoverGrey')
This doesn't work, though, because the effect isn't caused by a class. It's caused by a pseudoclass. Pseudoclasses can't be added programmatically.
One workaround is to create a new actual class with the exact same definition as the pseudoclass. In my case, the pseudoclass is a.list-group-item:hover, defined in bootstrap.css.
a.list-group-item:hover,
a.list-group-item:focus {
text-decoration: none;
background-color: #f5f5f5;
}
I edited bootstrap.css to make a new (actual) class, bootstrapMouseoverGrey, with the same definition as the pseudoclass.
a.list-group-item:hover,
a.list-group-item:focus,
.bootstrapMouseoverGrey {
text-decoration: none;
background-color: #f5f5f5;
}
Now, I can just add this class to an element using the line at the top of the answer. This gives me the result I want. Works like a charm!
Using jQuery:
var event = jQuery.Event('<event_name>');
event.stopPropagation();
$('<selector>').trigger(event);
Taken from the docs.

Cannot position Google +1 button with CSS?

I'm having some trouble positioning the Google +1 button on my website. The div is as follows:
<div class="g-plusone"></div>
The CSS I'm using is pretty simple:
.g-plusone
{
position: absolute;
top:95px;
left:715px;
}
Despite what would seem straightforward, it simple does not want to move.
I know for a fact that the div in question is being accessed. What's strange is that other social sharing buttons, such as the FB like below follow the same syntax and are positioned perfectly.
.fb-like
{
position: absolute;
top:62px;
left:715px;
}
Adding !important to the values does nothing, unfortunately.
Any ideas?
When Google loads +1 button the .g-plusone class seems to disappear, so try to put this DIV inside another DIV, as illustrated below:
HTML:
<div class="google-button">
<div class="g-plusone"></div>
</div>
CSS:
.google-button
{
position: absolute;
top:95px;
left:715px;
}
After page loads, the Google div called g-plusone turns into a lot of code, but, you can manipulate this button with id generated.
In my case, for example, to align the button in the middle of the line I put:
#___plusone_0{
vertical-align: middle !important;
}
Note: The id ___plusone_0 is the id generated by the google codes. Do whatever you want with this id.
Use something like Firebug to ensure you're targeting the correct element. The +1 button is very deeply nested, so you'll most likely need to look further up the DOM tree to get to it's outermost wrapper. You will be able to set the position of that without needing to use !important or anything, so I would definitely check this first.
Sorry, I would have just added this as a comment above but I don't seem to be able :)

Change stylesheet based on month/season in jQuery

I'm trying to find a way to change stylesheets based on what season it is with jquery because at this point it is unknown if I can use php or ruby at all on this site. Thanks for your responses!
The simplest is to scope your CSS styles and add a class at a high level. I usually do this at the body element. The CSS looks like:
body.summer ul { background-color: green; }
body.fall ul { background-color: orange; }
body.winter ul { background-color: white; }
body.spring ul { background-color: pink; }
Then, use JS to set the body class:
...</body>
<script ...>
var season = (new Date()).getMonth...;
$('body').addClass(season);
</script>
</html>
As you can see, I placed this immediately after closing the body tag. I think this is the first place you can put it and get it to work, but you'll have to check. The reason to put it here is to prevent the flash of unstyled content-- if you have lots going on on the page, you'll want to execute this Javascript before the on ready callback. That being said, I actually haven't had much problem just putting most of my code in the ready callback.
You can also load different stylesheets easily-- probably at the same place. Just create a style node and insert it into the head as the last node. You'd do this if you have major differences between your styles. Pretty tricky to maintain.
$("head").append("<style type=\"text/css\" src=\"" + season + ".css\"">");
I would suggest you narrow down the items that you want to change on the page, since the CSS file would already be loaded and jQuery would just be applying the css after the static css is loaded. You could leave these specific style declarations out of the css or keep them as default. For example, if the background image changes, you could set it to white in the default css declaration. This way, on load, it looks normal and you're only using JavaScript to load necessary items.
You could then use the JavaScript month function to get the current month
var month = new Date();
month = month.getMonth();
Then, you could use jQuery to apply those styles to the head with the jQuery ready function. You could have a simple switch of if/else statement to select one of four statements depending on the month number. For example, if you want to change the background
$("head").append("<style type=\"text/css\">body {background-color: #FFF !important;}</style>");
Just a quick example, but it would make it more efficient than loading a whole sheet I think.
put all your declarations in one css at the form of
.someStyle{ color:blue;}
.summer .someStyle{color:yellow;}
.winter .someStyle{color:purple;}
...
all classes under .summer will override the default style for summer
then on the server/client when the page is ready - add this class to the body
the only problem with doing it at the client is that the default style will render first and then switch to the new one (just pick the season most common to your site's users - if it was Israel i would choose summer ;-)

Categories

Resources