This is my first attempt at JavaScript, so I am looking to learn.
I have a website that has jQuery built in and I wanted to leverage that in the following way:
- I want to get a number variable that precedes a certain text string (
*n*/portal.css
) - Get the name of the current webpage
- Use this number and pageName to help build a URL to a specifically named image file The image will have the same name as the webpage with an "_hd.jpg" appended to it
- Check if the image file exists and if it does add this image to a CSS div background otherwise do nothing
<script>
$(function () {
$(document).foundation();
//get webpage name
var loc = window.location.href
var fileNameIndex = loc.lastIndexOf("/") + 1;
var dotIndex = loc.lastIndexOf('.');
var pageName = loc.substring(fileNameIndex, dotIndex < fileNameIndex ? loc.length : dotIndex);
//get number variable
var head = document.head
var portalCss = head.innerHTML.match(/\/[0-9]+\/portal.css/);
var portalNum = portalCss[0].replace("/", "")
portalNum = portalNum.replace("portal.css", "")
//build url for image
var HeaderImgUrl = '/Portals/' + portalNum + '/Images/' + pageName + '_hd.jpg'
//check if image exists and assign css values to css class RowPageHeader
$.ajax({
url: HeaderImgUrl, //or your url
success: function (data) {
$(".RowPageHeader").css("background-image", "url(" + HeaderImgUrl + ")");
$(".RowPageHeader").css("background-position", "center top");
$(".RowPageHeader").css("background-size", "100% auto");
$(".RowPageHeader").css("background-repeat", "no-repeat");
$(".RowPageHeader").css("overflow", "hidden");
},
})
var FooterImgUrl = '/Portals/' + portalNum + '/Images/footer_bg.jpg'
$.ajax({
url: FooterImgUrl, //or your url
success: function (data) {
$(".RowFooter").css("background-image", "url(" + FooterImgUrl + ")");
$(".RowFooter").css("background-position", "center top");
$(".RowFooter").css("background-size", "2000px auto");
$(".RowFooter").css("background-repeat", "no-repeat");
$(".RowFooter").css("overflow", "hidden");
},
})
})
</script>
Two questions:
- How can I improve this code?
- I want to move the CSS rules into a CSS class in the pages skin.css file. How can I add a CSS class to the existing one that I am adding the CSS rules to?