I created a button that will randomly appear on the screen (per my boss’s request) that when clicked will open an email in order to provide feedback.
My goal is to make this script do everything, mainly so I don’t have to access the ASP markup or CSS files for each website. Just throw the script in the header and place the image in the folder.
I created the script to:
- Create a div that contains the button
- set the CSS for the elements of that div (there will be a little image next to some text)
- appear to the user at random
The script I came up with works fine, however, I was wondering if there was anyway I can clean this up at all. (I’m kind of new to writing my own Jquery scripts and I’m trying to learn how to be as organized as possible.)
Jquery:
$(function () {
var fbContainer = $('<div id="feedback"><img src="image.gif" /> <a href="mailto:feedback@mywebaddress.com">Feedback</a></div>')
.css({
'display': 'none',
});
$('#header').append(fbContainer);
$('#feedback a').css({
'font-family': 'arial',
'float': 'left',
'text-decoration': 'none',
'color':'#000000'
});
$('#feedback img').css({
'float': 'left',
'margin': '3px 5px 0 0';
});
var randofactor = .5;
var randomizer = Math.random();
if (randomizer < randofactor) {
fbContainer.css('display', 'block');
}
});
Thanks for any assistance
You could try encapsulating your code inside a javascript object, which I would recommend placing inside a separate file. I would suggest moving the header where the button is placed to be parametrized inside a constructor function, so you can reuse it elsewhere.
Separating the various logical parts such as object creation and styling into their own functions also helps readability of your code.