Using a JavaScript function with CSS via <style> - javascript

I am working on a simple slideshow. I am using Javascript for the process of the slideshow and CSS for display of it. For some reason the CSS shows the first image perfectly but the JavaScript function is not engaging with the CSS to change the images. Suggestions?
Here is my code:
<body>
<style scoped id="slider">
html{
background: url('Africa Twin Mountainside.jpg') no-repeat center center fixed;
background-size: cover;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
}
</style>
<script type="text/javascript">
var images = [
"Africa Twin Mountainside.jpg",
"FZ-10.jpg",
"GSXR track.jpg",
"Pioneer 1k mountain.jpg",
"Raptor sand.jpg"
];
var step = 0;
function slideit(){
var imageUrl = images[step];
document.getElementById('slider').src = background;
step++;
if(step>=images.length)
step=0;
setTimeout("slideit()", 1000);
}
slideit();
</script>
</body>

This should work for you:
var images = [
"Africa Twin Mountainside.jpg",
"FZ-10.jpg",
"GSXR track.jpg",
"Pioneer 1k mountain.jpg",
"Raptor sand.jpg"
];
function slideit(step){
document.getElementById('slider').src = images[step || 0];
step++;
if(step === images.length) {
step = 0;
}
setTimeout(function() {
slideit(step);
}, 1000);
}
slideit();

This is going to be somewhat long, but hopefully this will point you in the right direction to rework your solution properly.
I'll start with this: <style scoped id="slider">
Firstly, the scoped attribute for <style> tags are currently only supported by Firefox, so I would avoid it altogether for the time being. The purpose of the scoped attribute is to constrain the style to the enclosing element, but you can easily do the same thing with the class attribute instead.
Since this is a simple, single-page idea you're implementing, it's perfectly acceptable to use <style> tags directly in your html document, but in general, it's better to create a separate css stylesheet and attach it to your page with a <link> tag. If you do include styles in the html document, it would typically be found inside the <head> tag.
Additionally, I don't think I've ever seen someone declare styles for the html tag; from my experience that's typically used for the body tag instead, but perhaps someone more knowledgable that I can comment on that.
Lastly, you've given this style tag an id, however I can think of no practical use for this, and when you try to manipulate it in your javascript with document.getElementById('slider').src = background;, you're selecting this <style> block - which doesn't have a src attribute, so that piece of code does nothing at all.
What you really want to use here is an <img> tag, which does have a src attribute that can be manipulated - you were on the right track here, but used the wrong tools. I would ditch the <style> element you have here altogether and just use an <img> like so:
<img id="slider" src="Africa Twin Mountainside.jpg">
You can then style this in css:
#slider {
width: 100%;
height: auto;
margin: auto;
}
This will scale up your image to take up the entire width of the browser; the size can be adjusted to your preference. It will also center your image in the browser if you choose a width < 100%.
Now we can look at your script. Peter Chon's answer is a well-written, working solution that will work when combined with the <img> tag that I've written above, and is essentially the same thing I would have written. You almost had the script part right, and if you compare what's written in Peter's answer to yours you can see that you were nearly on the mark. He would probably be willing to explain further if you have questions.
You had the methodology for how to implement your slideshow (mostly) correct, but the execution didn't work because you didn't understand what tools to use to get the job done. W3Schools get's a bad rap around these parts, but it's not a bad place to start if you're looking to learn about the basics without investing in a book, and if you read through their tutorials you can get at least a basic understanding of how tags and their attributes can be used to accomplish things.
If I had book references I'd provide them, but I don't. One that I considered getting was "HTML and CSS: Design and Build Websites" by John Duckett. It's got good reviews on Amazon, but I haven't read it personally.

Related

Standardize image into div

I'm working with Bootstrap and I want to put some photos into my div and I want them to be all at the same size ("standardize").
If they're too big (and they will always be) I want to resize them to fit in my div and crop them if necessary.
For the moment her is what I do :
I've tried to change the style of the image in jQuery in a function:
• If the height is bigger than the width, I switch the style to max-width:100% and height auto.
• Inversement if the width is bigger than the height.
But I'm still new to jQuery and I am probably doing something wrong; can someone light my lantern please?
Here is my jQuery
$(document).ready(function(){
photoResize();
$(window).resize(function(){
photoResize();
});
});
function photoResize(){
image_w = $('img').width();
image_h = $('img').height();
if(image_h > image_w)
{
$('img').css("max-width","100%");
$('img').height("auto");
}
else if(image_w > image_h)
{
$('img').css("max-height","100%");
$('img').width("auto");
}
}
And here is a Fiddle for a better view : https://jsfiddle.net/Baldrani/DTcHh/9801/
Simplicity
I do this quite often in the CMS we use at work for galleries etc. The method I use involves a jQuery library called imgLiquid.js.
This will turn an inline image into a background image on the parent div. It's good because you can achieve your desired effect. It will crop the image (as it technically becomes a background image) and will apply background-size: cover; and background-position: center center; as inline styles.
You can find the plugin here
To initialize the plugin you just need:
$(".myele").imgLiquid();
Overheads
The plugin is very small (roughly around 5.106 KB) so you don't need to worry about adding weight to the page. It really it the most simple method I've come across (bar using thumbnails generated from the sever-side - see note at the bottom).
Cue CSS
I've tested this thoroughly and found it gives excellent results. You may then ask... what happens to my parent divs (as technically the plugin hides the img element - which therefore means the parent element doesn't know what height to make itself).
An easy method to make things work responsively, or not:
.myelement:before{
content: "";
padding-top: 50%;
display: block;
}
This CSS will give your heights back to the wrapping element. So if you wanted certain proportions you could use this math:
h / w * 100 = your percentage for the padding-top.
Working Example
Small note
Technically if I had the control I'd advise just using thumbnails.. I assume you're using some sort of system that could technically just render cut down versions of the images? The reason I use this method — and suggested it — is that I don't have control over the CMS and I'm assuming you just want to manage the code that's being produced as it's not stated.
if you want to make your images the same size then you dont need any javascript or calculations, why not just set it in css?
.someUniqueContainer img{
width:300px;
height:300px; // or what ever height you want
}
I'm guessing that in reality you actually want to crop all your images to a set width/height. if that's the case you'll need a serverside script for that.
where are the images coming from? it would be easyer to just edit them. if they are coming from a user then you would resize/crop on the server on file upload
There were several mistakes in your code.
Please look at this jsfiddle, please see https://jsfiddle.net/DTcHh/9796/
$(document).ready(function () {
photoResize();
$(window).resize(function () {
photoResize();
});
});
function photoResize() {
image_w = $('img').width();
image_h = $('img').height();
if (image_h > image_w) {
$('img').css("max-width", "100%");
$('img').height("auto");
} else if (image_w > image_h) {
$('img').css("max-height", "100%");
$('img').width("auto");
}
}
sth like this?, although this is pure css, not jquery included, might not be suit in your case..
body {
margin-top:20px
}
.col-xs-3 {
margin: 5px 0;
width: 500px;
height:120px
}
.col-xs-3 > div {
width: 100%;
height: 120px;
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
JsFiddle

Override HTML-standardized image width, prevent third-party JS blown up photo?

I host my website on Blogger and have a basic understanding of HTML and CSS. I want to add a collaborative add-your-link thingamajig with SimplyLinked. However...
The HTML they gave me was this:
<script type="text/javascript" src="http://www.simply-linked.com/listwidget.aspx?l=60A7D397-F94E-4840-8DFE-BCCB40BA298F"
></script>
But because I have HTML set the width for every photo posted to my website to be 800px, what really should be a small button at the bottom of the list ends up horribly oversized. See pic here.
How can I (or indeed, can I) override the HTML that programs the body of my blog so that the images in third-party javascript are their proper size?
Thank you!!
[EDIT 7/2/14 12:16 AM]
I so appreciate the responses and am quickly realizing just how little I know about this. Thank you for your help and your patience!
Wyzard: You're absolutely right – it is CSS. (I'm still learning!)
ejay_francisco: The CSS (as Wyzard correctly pointed out) is added right before the end of the skin. It's a ton of code, I don't think I can post the whole thing here..? But maybe this excerpt is helpful:
.post-body img {
width: 800px!important;
height: auto!important; }
#sidebar-left-1 {margin: 0 0px 0 -10px;
}
#Blog1 {margin: 0px 0px 0 30px;
}
#HTML6{
margin:60px 0 0 0px;
}
#navbar, #Attribution1{
display:none;
}]]></b:skin>
You can add this code to your HTML (preferably the <head>, but <body> would work):
<style>
.sl_i a img {
width: 181px;
height: 28px;
}
</style>
…Or even better, add it to your CSS, without the <style> and </style> tags.
Feel free to delete the newlines (carriage returns) and reduce strings of multiple spaces down to a single space if you'd like to conserve space:
<style>.sl_i a img{width:181px;height:28px;}</style>
What it does is target any <img> element nested inside an <a> element nested inside an element of class sl_i. I got that definition by opening the href in a browser window, inspecting the image, and noting its position in the DOM.
DEMONSTRATION: http://jsbin.com/gefiq/1/

how to detect screen resolution in javascript

i want let the javascript to detect the screen resolution itself because i might have different LCD and each of them are in different size. this is the code temporary i have.
<html>
<head>
<title>ViewImage</title>
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
</head>
<body onload="JavaScript:timedRefresh(1);">
<img src = "screenshot.jpeg" width="1014" height="751">
</body>
</html>
i have try to put the javascript into the code
<img src = "screenshot.jpeg" <script type="text/JavaScript">"width ="screen.width </script>>
but it failed. when i open that, i wish it can get the resolution itself at the can anyone help me with this problem ? thanks in advance
You seem to have a few problems with your code:
You can remove JavaScript: from your onLoad event, this is used within hyperlinks
<a href="javascript: doSomething()" />Link</a>
Also you are trying to refresh the page every 1 millisecond (if you are trying to refresh every second you should change it to 1000).
Your function would be better written like this so you avoid using eval:
function timedRefresh(timeoutPeriod) {
setTimeout(function() {
location.reload(true);
}, timeoutPeriod);
}
In your case, this would suffice:
<img src = "screenshot.jpeg" width ="100%" />
jsFiddle Demo
Of course this will only do what you want if body is the same size as the viewport. This basically tells the browser that the img should be just as big as its parent (in this case the body).
Note: Javascript does not work the way you expect it. <script> is an HTML element, that lets you embed scripts (Javascript mostly) into your document. You cannot change the HTML source with Javascript on the client side (like you can with PHP, Python, etc. on the server side). You can modify the DOM though.
You can try this
window.screen.availHeight for getting height
window.screen.availWidth for getting width
Thanks.
The CSS3 'size' and 'cover' properties also help in this situation only if you are not much worried about older versions of IE. And no need to use any JavaScript
Demo - http://jsfiddle.net/fHwu8/
body{
background: #000 url(http://www.psdgraphics.com/wp-content/uploads/2009/02/abstract-background.jpg) left top fixed no-repeat;
background-size: 100% 100%;
-moz-background-size: 100% 100%; /*cover*/
-webkit-background-size: 100% 100%;
-o-background-size: 100% 100%;
}
try:
window.screen.availHeight
window.screen.availWidth

How to override HTML image using CSS

I have my current code:
#content img[src="/img/test.gif"] {
background-image:url(dark-img.png) !important;
}
From my understanding !important; overrides existing values?
Why isn't this overriding the current HTML image in place there? The background shows up, behind the HTML image.
I want it in front of the HTML image, is this possible using CSS or JS?
Edit: For what its worth, im making a userscript that will modify the existing style of the site. So I do not have direct access to the HTML image.
You don't need javascript for image replacement! As long as you can identify the image by a CSS selector, you can use CSS to do the trick.
See the solution here
http://www.audenaerde.org/csstricks.html#imagereplacecss
Here is the code using only css:
<img src="tiger.jpg"
style="padding: 150px 200px 0px 0px;
background: url('butterfly.jpg');
background-size:auto;
width:0px;
height: 0px;">
sets the image size to 0x0,
adds a border of the desired size (150x200), and
uses your image as a background-image to fill.
If you upvote this answer, give #RobAu's answer an upvote, too.
The replacement of an image in CSS can be done in several ways.
Each of them has some drawbacks (like semantics, seo, browsercompatibility,...)
On this link 9 (nine!) different techniques are discussed in a very good way :
http://css-tricks.com/css-image-replacement/
If you are interested in css in general : the whole site is worth a look.
The background-image property, when applied to an image, refers to (drum roll ... ) the background-image of the image. It will always be behind the image.
If you want the image to appear in front of the image, you are going to have to use two images, or another container with a background-image that covers the first image.
BTW, it is bad practice to rely on !important for overriding. It can also be ineffective since 1) it can't override declarations in an element's style attribute, and 2) it only works if it can work based on the markup and the current CSS. In your case, all the huffing and puffing and !important declarations won't make an image do something it can't do.
I answered a similar question in another SO page..
https://robau.wordpress.com/2012/04/20/override-image-src-in-css/
<img src="linkToImage.jpg" class="egg">
.egg {
width: 100%;
height: 0;
padding: 0 0 200px 0;
background-image: url(linkToImage.jpg);
background-size: cover;
}
So effectively hiding the image and padding down the background. Oh what a hack but if you want an with alt text and a background that can scale without using Javascript?
Use your 'userscript' to change 'src' attribute value.
If there is an ID there, you can do this:
document.getElementById('TheImgId').src = 'yournewimagesrc';
If there is no ID:
var imgElements = document.getElementsByTagName('img');
Do iteration of imgElements. When its src value is match with your criteria, change the value with your own, do break.
Update:
Javascript:
<script language="javascript">
function ChangeImageSrc(oldSrc, newSrc) {
var imgElements = document.getElementsByTagName('img');
for (i = 0; i < imgElements.length; i++){
if (imgElements[i].src == oldSrc){
imgElements[i].src = newSrc;
break;
}
}
}
</script>
HTML:
<img src="http://i.stack.imgur.com/eu757.png" />
<img src="http://i.stack.imgur.com/IPB9t.png" />
<img src="http://i.stack.imgur.com/IPB9t.png" />
<script language="javascript">
setTimeout("ChangeImageSrc('http://i.stack.imgur.com/eu757.png', 'http://i.stack.imgur.com/IPB9t.png')", 5000);
</script>
Preview:
The first image will be replaced after 5 secs. Try Live Demo.
you'll have to place the first image as a background-image too. Then you can override it. You could do in a "standard" css file for the site, and every user gets its own, where he can override what he wants.
i agree with all the answers here, just thought id point out that 'browsers' such as IE won't like the img[src="/img/test.gif"] as a means of selecting the image. it would need a class or id.
The images shown in tags are in the foreground of the element, not the background, so setting a background image in an won't override the image; it'll just appear behind the main image, as you're seeing.
What you want to do is replace the image. Here's your options:
Start with an element with a background image, not an tag. Then changing the background image in CSS will replace it.
Start with an tag, but use Javascript to change the src attribute. (this can't be done in CSS, but is simple enough in JS)
EDIT:
Seeing your edit in the question, I'd suggest option 2 - use Javascript to change the src attribute. It's quite simple; something like this would do the trick:
document.getElementById('myimgelement').src='/newgraphic.jpg';
You should be able to replace it by just doing something like:
.image {
content: url('https://picsum.photos/seed/picsum/400');
width: 200px;
height: 200px;
}
Unfortunately seems that it does not work in Firefox :(

jQuery: Load background image from css class into variable?

How can I load the background-image (url) from a css class into a JavaScript variable (preferably using jQuery) ?
Example:
.myCssClass { background-image: url(/images/checkered.gif) no-repeat; }
...and now load checkered.gif into a var CheckeredGraphic = ??? using JavaScript.
One way you could do it is to just ask jQuery what the background image is. If you don't have any elements with class myCssClass perhaps just generate one and don't add it to the DOM.
var checkeredGraphic = $('<div class="myCssClass"></div>').css("backgroundImage");
I haven't tested that, but if it doesn't work, perhaps add it to the body with a large negative margin so it doesn't render on screen.
That line above will return url(/images/checkered.gif) so then you could just use a regex to clean it up:
...css("backgroundImage").replace(/url\(['"]?([^\)'"]+)['"]?\)/, "$1")
Also, your css definition is wrong. It should be:
background-image: url(...);
background-repeat: no-repeat;
You can access CSS properties from JavaScript pretty easily. Check this out for an in depth explaination: http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript

Categories