Button with image and text [duplicate] - asp.net

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Text on an Image button in c# asp.net 3.5
I want a asp.net button with text on left and image on right

Here's one I wrote:
public class WebImageButton : LinkButton, IButtonControl
{
protected override void OnPreRender(EventArgs e)
{
if (!this.DesignMode)
{
// Apply the image
if (this.Image.Length > 0)
{
this.Style.Add("background-image", "url(" + this.Image + ")");
this.Style.Add("background-repeat", "no-repeat");
this.Style.Add("background-position", this.ImageHorizontalOffset + " " + this.ImageVerticalOffset);
}
}
base.OnPreRender(e);
}
[DescriptionAttribute("The path to the default image to be displayed.")]
public string Image
{
get
{
if (_image == null)
{
return string.Empty;
}
return _image;
}
set
{
_image = value;
}
}
private string _image;
[DescriptionAttribute("The unit to offset the image by horizontally.")]
public string ImageHorizontalOffset
{
get
{
return _imageHorizontalOffset;
}
set
{
_imageHorizontalOffset = value;
}
}
private string _imageHorizontalOffset = "0px";
[DescriptionAttribute("The unit to offset the image by vertically.")]
public string ImageVerticalOffset
{
get
{
return _imageVerticalOffset;
}
set
{
_imageVerticalOffset = value;
}
}
private string _imageVerticalOffset = "center";
}
Then the CSS that accompanies it:
.ImageButton
{
background:#666;
border:solid 1px #000;
color:#FFF;
font-size:10pt;
font-weight:bold;
padding:4px;
text-align:center;
cursor:hand;
}
And an example of its use:
<ctrl:WebImageButton ID="WebImageButton1" runat="server"
OnClick="WebImageButton1_Click" CssClass="ImageButton" Text="Click me"
ImageHorizontalOffset="4px" />

You could use CSS to apply the image to the background of the input element. Have a read up in the background-image CSS method:
http://www.w3schools.com/css/pr_background-image.asp

I'm not sure if there are any asp controls that allow you to do this (but I could be wrong). What you will want to fool around with is possibly divs and their onclick events. Then you can do something like onclick="Javascript:this.form.submit();". You will be able to size the div how you please and insert what you want (in your case text and an image).
Edit: Then in the css you could also add #mydiv:hover { cursor: pointer; } To get the hand icon when users move their cursor over the div.
But it looks like gage provided a link to someones solution :P Good luck

Related

Style.Visibility doesnt let element do animation?

I have two functions which should hide and make my element (Image), whose id is "Brandish":
hideBrandish(): void {
document.getElementById('Brandish').style.visibility = 'hidden';
}
showBrandish(): void {
document.getElementById('Brandish').style.visibility = 'visible';
}
Now I have a function, that calls first this.showBrandish().
Then I have a function, that calls the .className = 'skillimage', which moves the image per #keyframes:
this.moveSkillImage(); {
if (this.chosenHero.skill.name === 'Brandish') {
document.getElementById('Brandish').className = 'skillImage';
}
}
Finally I call hideBrandish().
The problem is that my animation isn't processing, instead my image just gets hidden. Why is that?

Highlight Dates in Rich:calendar

I have a calendar which is working fine. it displays records on click and changes the colour to green or red. if records are available date will become red colored.
I don't want onclick I want calendar to displays date colours on
calendars onload event.** KIndly help. following is my code . I think problem with css, I guess
.postive-records .rf-cal-sel {
background-color: green;
}
.no-records .rf-cal-sel {
background-color: red;
}
<rich:calendar styleClass="#{eventMaster.eventMasterList!=null and eventMaster.eventMasterList.size()>0?'postive-records':'no-records'}" locale="EN"
id="searchDateCalendarcommon" popup="false"
showApplyButton="false" datePattern="dd/MM/yyyy"
value="#{eventMaster.eventSearchDate}" >
<rich:tooltip followMouse="false"
showDelay="100"
direction="topRight"
layout="block"
onmouseover="">
<h:outputText value="#{eventMaster.calendarTooltipText}"
style="color: red;font-size: 12px;"/>
</rich:tooltip>
<f:ajax event="change" listener="#{commonOutputContentBean.showEvents()}"
render="cmnoplayoutfrm searchDateCalendarcommon" />
</rich:calendar>
The calendar simply displays days in a month, it isn't linked to any data. Furthermore styleClass is applied to the entire calendar not to the cells. You need to provide a dataModel.
The datamodel has to implement org.richfaces.model.CalendarDataModel, and you also need to implement org.richfaces.model.CalendarDataModelItem for the days which is a plain object with getters and setters. The CalendarModel would be something like this:
public class MyCalendarModel implements CalendarDataModel {
private boolean hasEvents(Calendar calendar) {
// …
}
#Override
public CalendarDataModelItem[] getData(Date[] dateArray) {
CalendarDataModelItem[] modelItems = new MyCalendarModelItem[dateArray.length];
Calendar current = GregorianCalendar.getInstance();
Calendar today = GregorianCalendar.getInstance();
today.setTime(new Date());
CalendarModelItem modelItem;
for (int i = 0; i < dateArray.length; i++) {
current.setTime(dateArray[i]);
modelItem = new MyCalendarModelItem();
if (hasEvents(current)) {
modelItem.setStyleClass("postive-records");
} else {
modelItem.setStyleClass("no-records");
}
modelItems[i] = modelItem;
}
return modelItems;
}
#Override
public Object getToolTip(Date date) {
return null;
}
}
You can check the example in the showcase.

HtmlGenericControl("br") rendering twice

I'm adding some content to a given web page from code behind. When I want to add a break after some text, I try to do that this way:
pDoc.Controls.Add(New Label With {.Text = "whatever"})
pDoc.Controls.Add(New HtmlGenericControl("br"))
,where pDoc is the Panel in which I'm adding the content. But it adds two br tags into the final HTML.
I've avoid this behaviour this way:
pDoc.Controls.Add(New Label With {.Text = "whatever" & "<br />"})
Anyway, I'm so curious and I want to know why
pDoc.Controls.Add(New HtmlGenericControl("br"))
is acting that way. I also think my approach is not too fancy.
Regards,
Actually you can use;
pDoc.Controls.Add(new LiteralControl("<br/>"));
Whereas new HtmlGenericControl("br") adds two <br>, this will only add <br/> tag to your HTML so that you just have 1 space line.
In this picture I added those breaks with that code block.
Also similar question here: Server control behaving oddly
After some testing it looks like the reason is that HtmlGenericControl doesn't support self closing. On server side the HtmlGenericControl("br") is treated as:
<br runat="server"></br>
There is no </br> tag in HTML, so the browser shows it as there are two <br /> tags. Nice way out of this is to create HtmlGenericSelfCloseControl like this (sorry for C# code but you should have no issue with rewritting this in VB.NET):
public class HtmlGenericSelfCloseControl : HtmlGenericControl
{
public HtmlGenericSelfCloseControl()
: base()
{
}
public HtmlGenericSelfCloseControl(string tag)
: base(tag)
{
}
protected override void Render(HtmlTextWriter writer)
{
writer.Write(HtmlTextWriter.TagLeftChar + this.TagName);
Attributes.Render(writer);
writer.Write(HtmlTextWriter.SelfClosingTagEnd);
}
public override ControlCollection Controls
{
get { throw new Exception("Self closing tag can't have child controls"); }
}
public override string InnerHtml
{
get { return String.Empty; }
set { throw new Exception("Self closing tag can't have inner content"); }
}
public override string InnerText
{
get { return String.Empty; }
set { throw new Exception("Self closing tag can't have inner text"); }
}
}
And use it instead:
pDoc.Controls.Add(New Label With {.Text = "whatever"})
pDoc.Controls.Add(New HtmlGenericSelfCloseControl("br"))
As a simpler alternative (if you have reference to the Page) you can try using Page.ParseControl:
pDoc.Controls.Add(New Label With {.Text = "whatever"})
pDoc.Controls.Add(Page.ParseControl("br"))

How to change the rendering of a Menu Item in ASP.NET 4

Instead of rendering the image of a menu item as an <img> tag within an anchor, I'd like to add a class to the anchor tag which adds the image as a background image.
At the moment, I'm doing some post-processing with javascript that searches for image urls. If found, they are removed and replaced with a CSS class.
Is there a way to perform this by overriding the Menu or implementing a MenuAdapter?
I've had a look at the MenuAdapter class but it looks like I'd have to re-implement all rendering functionality just to change this small part.
[Note: the reason I'm doing this is because I want to display the images after the text; i struggled to do this using the default rendering.]
ETA: Answered below.
I found the simplest way is to override the Render method of the Menu.
Using this menu, you can put a tooltip and css class, separated by a semi-colon, in the ToolTip property of the menu item:
item.ToolTip = "this is the tip; class1 class2";
Note: This is a simplistic menu that performs as much as I want it to do. It ignores ImageUrl and SeparatorImageUrl.
public class CSSItemMenu : Menu
{
protected override void Render(HtmlTextWriter writer)
{
this.PerformDataBinding();
writer.Write(string.Format("<div id=\"{0}\" class=\"{1}\">", base.ClientID, base.CssClass));
writer.WriteLine();
writer.WriteLine("<ul class=\"level1\">");
foreach (MenuItem item in Items)
{
WriteItem(writer, item, 1);
}
writer.WriteLine("</ul>");
writer.WriteLine("</div>");
}
private static void WriteItem(HtmlTextWriter writer, MenuItem item, int level)
{
writer.WriteLine("<li>");
string title = "";
var userClass = "";
if (!string.IsNullOrEmpty(item.ToolTip))
{
var data = item.ToolTip.Split(';');
title = string.Format(" title=\"{0}\"", data[0].Trim());
if (data.Length > 1)
{
userClass = " " + data[1].Trim();
}
}
var cssClass = string.Format("class = \"popout level{0}{1}\"", level, userClass);
writer.WriteLine(string.Format("<a {0} href=\"{1}\"{2}>{3}</a>", cssClass, item.NavigateUrl, title, item.Text));
if (item.ChildItems.Count > 0)
{
writer.WriteLine(string.Format("<ul class=\"level{0}\">", level + 1));
foreach (MenuItem child in item.ChildItems)
{
WriteItem(writer, child, level + 1);
}
writer.WriteLine("</ul>");
}
writer.WriteLine("</li>");
}
}

Displaying CSS images in div updated by Ajax

I wonder if anyone can help. An HTML div in a page of mine contains a tree control which is shown or hidden depending upon a button pressed by a user. The button triggers an Ajax event which sets a variable on the server to show or hide the tree so that the state is persisted.
But here's the problem; when the tree is re-displayed, the icons for expanding / collapsing brances are not present. So far, I've not been able to work out why this is the case.
The tree is shown below: the first graphic shows the tree as it should be, the second shows it after it has been hidden and re-displayed.
alt text http://www.dcs.bbk.ac.uk/~martin/Tree_with_icons.png
alt text http://www.dcs.bbk.ac.uk/~martin/Tree_without_icons.png
The tree's HTML is built on the server as a list and each list item has a class reference to CSS as follows:
ul.tree li.liOpen .bullet {
background: url(myApp_Minus.png) center left no-repeat;
cursor: pointer;
}
ul.tree li.liClosed .bullet {
background: url(myApp_Plus.png) center left no-repeat;
cursor: pointer;
}
ul.tree li.liBullet .bullet {
background: url(myApp_Hyphen.png) center left no-repeat;
cursor: pointer;
}
Can anyone advise a method of showing the icons when the tree is re-displayed?
I've tried putting a link to the CSS file in the div, inline CSS elements and so on but without success.
Any help would be welcome.
I attach an extract of the tree's HTML at runtime:
<td align = "left">
<div id = "tree"><ul class = "tree" id = "navTree">
<li class = "liOpen">
<a href = "/myDataSharer/aboutConcept#communities">
<img alt = "Community" src = "/myDataSharer/images/myDataSharer_Community_Small.png">
</a>&nbsp
Martin
<ul>
<li class = "liOpen">
<a href = "/myDataSharer/aboutConcept#datasets">
<img alt = "Tabular dataset" src = "/myDataSharer/images/myDataSharer_TabularDataset_Small.png">
</a>&nbsp
Planets
</li>
<ul>
<li>
<a href = "/myDataSharer/aboutConcept#QAV">
<img alt = "Visualisation" src = "/myDataSharer/images/myDataSharer_Visualisation_Small.png">
</a>&nbsp
Test QAV
</li>
<li>
<a href
The tree itself is in a div called 'tree' which is updated from Javascript method as follows:
document.getElementById("tree").style.visibility = "visible";
document.getElementById("tree").innerHTML = str;
The Javascript for the tree is:
/* WRITTEN BY: Martin O'Shea for myDataSharerAlpha.
*
* This program has been inherited verbatim from the original author's sample code as mentioned
* below. No changes have been made other than a rename of a variable on line 121 from 'mktree' to 'tree'.
* ===================================================================
* Author: Matt Kruse <matt#mattkruse.com>
* WWW: http://www.mattkruse.com/
*
* NOTICE: You may use this code for any purpose, commercial or
* private, without any further permission from the author. You may
* remove this notice from your final code if you wish, however it is
* appreciated by the author if at least my web site address is kept.
*
* You may *NOT* re-distribute this code in any way except through its
* use. That means, you can include it in your product, or your web
* site, or any other form where the code is actually being used. You
* may not put the plain javascript up on your site for download or
* include it in your javascript libraries for download.
* If you wish to share this code with others, please just point them
* to the URL instead.
* Please DO NOT link directly to my .js files from your site. Copy
* the files to your server and use them there. Thank you.
* =====================================================================
* HISTORY
* ------------------------------------------------------------------
* December 9, 2003: Added script to the Javascript Toolbox
* December 10, 2003: Added the preProcessTrees variable to allow user
* to turn off automatic conversion of UL's onLoad
* March 1, 2004: Changed it so if a <li> has a class already attached
* to it, that class won't be erased when initialized. This allows
* you to set the state of the tree when painting the page simply
* by setting some <li>'s class name as being "liOpen" (see example)
*
* This code is inspired by and extended from Stuart Langridge's aqlist code:
* http://www.kryogenix.org/code/browser/aqlists/
* Stuart Langridge, November 2002
* sil#kryogenix.org
* Inspired by Aaron's labels.js (http://youngpup.net/demos/labels/)
* and Dave Lindquist's menuDropDown.js (http://www.gazingus.org/dhtml/?id=109)
*/
// Automatically attach a listener to the window onload, to convert the trees
addEvent(window,"load",convertTrees);
// Utility function to add an event listener
function addEvent(o,e,f){
if (o.addEventListener){ o.addEventListener(e,f,true); return true; }
else if (o.attachEvent){ return o.attachEvent("on"+e,f); }
else { return false; }
}
// utility function to set a global variable if it is not already set
function setDefault(name,val) {
if (typeof(window[name])=="undefined" || window[name]==null) {
window[name]=val;
}
}
// Full expands a tree with a given ID
function expandTree(treeId) {
var ul = document.getElementById(treeId);
if (ul == null) { return false; }
expandCollapseList(ul,nodeOpenClass);
}
// Fully collapses a tree with a given ID
function collapseTree(treeId) {
var ul = document.getElementById(treeId);
if (ul == null) { return false; }
expandCollapseList(ul,nodeClosedClass);
}
// Expands enough nodes to expose an LI with a given ID
function expandToItem(treeId,itemId) {
var ul = document.getElementById(treeId);
if (ul == null) { return false; }
var ret = expandCollapseList(ul,nodeOpenClass,itemId);
if (ret) {
var o = document.getElementById(itemId);
if (o.scrollIntoView) {
o.scrollIntoView(false);
}
}
}
// Performs 3 functions:
// a) Expand all nodes
// b) Collapse all nodes
// c) Expand all nodes to reach a certain ID
function expandCollapseList(ul,cName,itemId) {
if (!ul.childNodes || ul.childNodes.length==0) { return false; }
// Iterate LIs
for (var itemi=0;itemi<ul.childNodes.length;itemi++) {
var item = ul.childNodes[itemi];
if (itemId!=null && item.id==itemId) { return true; }
if (item.nodeName == "LI") {
// Iterate things in this LI
var subLists = false;
for (var sitemi=0;sitemi<item.childNodes.length;sitemi++) {
var sitem = item.childNodes[sitemi];
if (sitem.nodeName=="UL") {
subLists = true;
var ret = expandCollapseList(sitem,cName,itemId);
if (itemId!=null && ret) {
item.className=cName;
return true;
}
}
}
if (subLists && itemId==null) {
item.className = cName;
}
}
}
}
// Search the document for UL elements with the correct CLASS name, then process them
function convertTrees() {
setDefault("treeClass","tree");
setDefault("nodeClosedClass","liClosed");
setDefault("nodeOpenClass","liOpen");
setDefault("nodeBulletClass","liBullet");
setDefault("nodeLinkClass","bullet");
setDefault("preProcessTrees",true);
if (preProcessTrees) {
if (!document.createElement) { return; } // Without createElement, we can't do anything
uls = document.getElementsByTagName("ul");
for (var uli=0;uli<uls.length;uli++) {
var ul=uls[uli];
if (ul.nodeName=="UL" && ul.className==treeClass) {
processList(ul);
}
}
}
}
// Process a UL tag and all its children, to convert to a tree
function processList(ul) {
if (!ul.childNodes || ul.childNodes.length==0) { return; }
// Iterate LIs
for (var itemi=0;itemi<ul.childNodes.length;itemi++) {
var item = ul.childNodes[itemi];
if (item.nodeName == "LI") {
// Iterate things in this LI
var subLists = false;
for (var sitemi=0;sitemi<item.childNodes.length;sitemi++) {
var sitem = item.childNodes[sitemi];
if (sitem.nodeName=="UL") {
subLists = true;
processList(sitem);
}
}
var s= document.createElement("SPAN");
var t= '\u00A0'; //
s.className = nodeLinkClass;
if (subLists) {
// This LI has UL's in it, so it's a +/- node
if (item.className==null || item.className=="") {
item.className = nodeClosedClass;
}
// If it's just text, make the text work as the link also
if (item.firstChild.nodeName=="#text") {
t = t+item.firstChild.nodeValue;
item.removeChild(item.firstChild);
}
s.onclick = function () {
this.parentNode.className = (this.parentNode.className==nodeOpenClass) ? nodeClosedClass : nodeOpenClass;
return false;
}
}
else {
// No sublists, so it's just a bullet node
item.className = nodeBulletClass;
s.onclick = function () { return false; }
}
s.appendChild(document.createTextNode(t));
item.insertBefore(s,item.firstChild);
}
}
}
Thanks.
The Ajax of the web page is shown below:
<script language="Javascript">
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla / Safari.
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE.
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatePage(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getQueryStr());
}
function getQueryStr() {
queryStr = "action=toggleTree";
return queryStr;
}
function updatePage(str) {
if (str == "false") {
// Hide tree buttons and tree.
document.getElementById("tree").style.visibility = "hidden";
document.getElementById("expColTreeButtons").style.visibility = "hidden";
}
else {
// Show tree buttons.
document.getElementById("expColTreeButtons").style.visibility = "visible";
// Show tree.
document.getElementById("tree").style.visibility = "visible";
document.getElementById("tree").innerHTML = str;
}
}
function toggleTree() {
// Make call to server to toggle tree.
document.getElementById("tree").innerHTML = "<img src='/myDataSharer/images/myDataSharer_Wait.gif' alt='Growing tree' />"
xmlhttpPost("/myDataSharer/toggleTree");
}
The Ajax above is triggered from a form which has three buttons. The 'Show / hide' button sees to things; the other two of the buttons are also enclosed within a div but they are alright.
<form>
<input class = "treeButton" type="submit" value="Show / hide" onClick = "toggleTree(); return false;">
<div id = "expColTreeButtons">
<input class = "treeButton" type="submit" value="Expand all" onClick = "expandTree('navTree'); return false;">
<br />
<input class = "treeButton" type="submit" value="Collapse all" onClick = "collapseTree('navTree'); return false;">
<br />
</div>
</form>
Your CSS looks fine ad like something that could produce the example on the left, so it must be the HTML or the JavaScript that does the showing and hiding. How does the JavaScript work?
It's not likely a CSS problem, since it's working the first time. I'd bet the problem lies in how your server is generating content - i.e. not assigning the proper attributes to each node.
This question has now resolved. Thanks those who contributed.
The solution was to re-process the Javascript tree after the div had been updated.

Resources