I'm trying to create a little script to allow me to set the style of a couple of menu items (done via a simple div with li items, which contain an each to send me to the correct page) but I'm not getting nowhere so I'm in need of help.
I have the following code on the master page:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="MILLS001_PAINEL.Site1" EnableTheming="True" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Title</title>
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="../js/menu.js"></script>
<link href="../css/reset.css" rel="Stylesheet" type="text/css" />
<link href="../css/style.css" rel="Stylesheet" type="text/css" />
<!--[if gte IE 9]>
<style type="text/css">
.gradient {
filter: none;
}
</style>
<![endif]-->
<asp:ContentPlaceHolder ID="head" runat="server"></asp:ContentPlaceHolder>
</head>
<body>
<div id="banner" class="gradient">
<div id="menu">
<ul>
<li>Painel de Gestão</li>
<li>Cockpit Operacional</li>
</ul>
</div>
<div id="logo"></div>
</div>
<div>
<asp:ContentPlaceHolder ID="Placeholder" runat="server">
</asp:ContentPlaceHolder>
</div>
</body>
</html>
The menu is defined in the master page, now I have this script to add certain classes (already created in CSS) to allow me to add/remove styles to the menu items:
$(document).ready(function () {
$('menu').find('li').hover(function() {
$(this).addClass("hovered");
},
function() {
$(this).removeClass("hovered");
});
$('menu').find('a').click(function(e) {
alert(e);
$(this).parent().addClass("active");
});
});
For some reason, I can't make this to work although I do not see any errors.
I had a problem with another script in which I had to reference names by using '[id$=name]', because Master page name mangling creates that problem, but it doesn't seem to be the case here...
Could anyone help me see what is wrong here?
Thanks in advance
EDIT
Got the hover thing working, but now I can't make to seem the active class to stay in place after the page refresh (apparently, a default behaviour of ASP).
You need to do:
$('#menu') <-- note the # sign
in your selectors.... Otherwise it looks like it should work OK
API Reference: jQuery ID Selector
To address your edit:
Element state is not automatically preserved between page loads. The browser doesn't look for "the same element" and try to make it appear the same. If you want the menu to remain open, you need to persist some data (whether through postback data or (I would recommend) some browser side state saving (e.g. localStorage)) and handle it manually in your menu code
Oh....rereading your question I think it might be simpler than that....
On page load, you could do something like:
$('[href=' + window.location.path + ']').addClass('active');
the window.location.path would likely need some pre-processing before the selector though to handle extra url parameters and variations of the path (e.g. ./index.html and index.html) in the href. However, note the various types of matching available with the attribute selector...namely *=...might make your href matching a lot easier...but I'm not gonna write all your code =0D
API Reference: jQuery Attribute Selector
Your selector looks incorrect, looks like your missing the # which notes it's an ID. Should be:
$('#menu').find('a').click()
And a slightly different approach:
$('#menu a').click()
Related
I don't want to use styles from style.css, so I decided to remove style.css from DOM. This work just fine in Firefox and IE8, but not in IE6:
$("LINK[href='http://www.example.com/style.css']").remove();
Any other solution, with jQuery?
Here is example:
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testing</title>
<script type="text/javascript" src="path/to/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("link[href*='style.css']").remove();
});
</script>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="content">...</div>
</body>
</html>
And here is CSS (style.css):
#content {
background-color:#333;
}
Only in IE #content is still dark. :(
Maybe is jQuery bug?
This is not a bug in jQuery, it is a bug (or possibly, a feature) of the IE rendering engine.
It seems this problem is being caused by the fact that Internet Explorer does not correctly re-render the page after removing the LINK element from the DOM.
In this particular case, the LINK tag is no longer present at the DOM, but IE still displays the CSS that has been loaded into memory.
A workaround / solution for this is to disable the stylesheet using the .disabled property like this:
// following code will disable the first stylesheet
// the actual DOM-reference to the element will not be removed;
// this is particularly useful since this allows you to enable it
// again at a later stage if you'd want to.
document.styleSheets[0].disabled = true;
EDIT in reply to your comment:
Or, if you want to remove it by the href use the following code:
var styleSheets = document.styleSheets;
var href = 'http://yoursite.com/foo/bar/baz.css';
for (var i = 0; i < styleSheets.length; i++) {
if (styleSheets[i].href == href) {
styleSheets[i].disabled = true;
break;
}
}
Perhaps it's something strange IE6 does to URL in the href attribute? Try something like:
$("LINK[href*='style.css']").remove();
(i.e. check whether the href value contains "style.css")
It's just a guess, however. If that doesn't work, I recommend checking the JQuery documentation closely on the subject of attribute selectors and the remove method.
Also keep in mind that it's also not impossible that it's in fact a bug. (IE6 in general causes lots of issues involving JavaScript and DOM manipulation, among other things.)
Topic's quite old, but You can only add ID to your link element, and delete it by element:
$("#id").remove();
Maybe using lowercase on the tag name?
( Answered: dont use <script type="text/javascript" src="jquery-1.8.0.min.js"></script> in html)
I am learning Jquery from this tutorial :
http://www.littlewebhut.com/javascript/getting_started/
I created One Html , 1 js file . put them on same physical folder ,put "jquery-1.8.0.min.js" in same folder , put a link of js file in html page
But it is not working .
my HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Demo</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Heading one</h1>
<p>This is just some text for heading 1</p>
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="my_code.js"></script>
</body>
</html>
My Jquery Page (my_code.js) :
$(document).ready(function(){
$("p").hide();
$("h1").click(function(){
$(this).next().slideToggle(300);
});
});
there is some minor mistake that is happening ,
I tried to search , but could not found relevant link .PLease suggest if I am missing something
Your code is working fine.There must be some problem with your jquery file path. Try including CDN hosted jquery library as follows or check your path:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
I have tried this on js fiddle and it's working fine I guess this is what you want ,right when on clicking the h1 tag you need that p to hide if I am not wrong ,
This is the js fiddle http://jsfiddle.net/Saranshshrma/7rzLW/1/
If this script is, small you can always put in, this
<script></script>
Tags before body content but remember put your Jquery before anything else any script or code you want to execute and you can post the chrome inspect element errors while executing this code
What error are you getting ? See the console/dev tools (f12) and notice you have to click the header text to trigger the effect:
http://jsfiddle.net/m5LL4/
$(document).ready(function(){
$("p").hide();
$("h1").click(function(){
$(this).next().slideToggle(300);
});
});
I did paste your code, just take a part of the html with the same jquery version and it works.
Is javascript enabled in your browser?
If you are using chrome Go Ctrl+H click on Setting in left side->show advanced Setting->Privacy->Content Settings->Allow all sites to run Javascript.
If already checked check for your jquery path file name.
I am attempting to code a simple example of a Dojo dialog box. I have copied the example shown in the Dojo reference here => http://dojotoolkit.org/reference-guide/1.7/dijit/Dialog.html
My code is shown below:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Dialog Test</title>
<script language="JavaScript" type="text/javascript">
dojo.require("dojo.parser");
dojo.require("dojox.widget.Dialog");
dojo.require("dijit.form.Button");
dojo.require("dijit.layout.TabContainer")
dojo.require("dijit.layout.ContentPane")
</script>
</head>
<body>
<div id="dialogOne" dojoType="dojox.widget.Dialog" title="My Dialog Title">
<div dojoType="dijit.layout.TabContainer" style="width: 200px; height: 300px;">
<div dojoType="dijit.layout.ContentPane" title="foo">Content of Tab "foo"</div>
<div dojoType="dijit.layout.ContentPane" title="boo">Hi, I'm Tab "boo"</div>
</div>
</div>
<p>When pressing this button the dialog will popup:</p>
<button id="buttonOne" dojoType="dijit.form.Button">Show me!
<script type="dojo/method" event="onClick" args="evt">
// Show the Dialog:
dijit.byId("dialogOne").show();
</script>
</button>
</body>
</html>
When the page loads in a browser, the Dialog doesn't work. I just see the text from the tabbed panes appear in the browser.
I've copied the code from the reference guide exactly so I'm very confused. Any suggestions?
Thanks.
James.
The Dojo samples unfortunately tend not to work fully 'as is', but are bits of skeleton code that need wrapping up in various standard bits of ceremony.
You've at least three things causing this not to work and render correctly. There may be other problems on top, but these will definitely cause it not to render:
You need to link to a version of the core Dojo scripts. Linking to a CDN version is a simple way to go. e.g. <script src="//ajax.googleapis.com/ajax/libs/dojo/1.8.3/dojo/dojo.js"></script>. Details are here: http://dojotoolkit.org/download/. Be sure to put this before your require scripting.
Add a link to a Dijit theme style sheet (CSS file) in your page, otherwise none of the widgets will display correctly. e.g. <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.8.3/dijit/themes/claro/claro.css"/>
Add a class attribute on the body element describing which theme you want to use. e.g. <body class="claro">.
Only when you've done all those three things will it have a chance of working. There may be other problems too, but they're the fundamental three.
I am dynamically adding markup to my application an example code below..
$(document).bind("pagechange", function (event, ui) {
var header = '<h3>' + appNames[i] + '</h3>';
var ulHeader = '<ul data-role="listview" id="myAppsGridTable" data-inset="true">';
..
$('.myBodyContent', ui.toPage).append(collapse + header + ulHeader + entire_list + '</ul>' + '</div>');
$('#NicksPage').trigger('create');
});
I have a reference to this page in my Default.aspx page and a reference to jquery mobile in the master page. When you navigate to Default the user sees raw unstlyed html added to the page then a flicker and the jquery mobile styles come in. Is there anyway I can get rid of displaying the unstlyed html to the user sees before the jquery mobile styles are added?
Here is a copy of my master page:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="UserMobile.master.cs" Inherits="User.Mobile.UserMobile" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head id="Head1" runat="server">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="Css/jquery.mobile.custom.structure.min.css" rel="stylesheet" type="text/css" />
<link href="Css/jquery.mobile.custom.theme.min.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<div data-role="page" data-theme="b" id="NicksPage">
<div data-role="header" data-position="fixed" data-theme="b">
<asp:ContentPlaceHolder ID="TopHeaderContent" runat="server"></asp:ContentPlaceHolder>
</div><!-- /header -->
<div data-role="content" class="myBodyContent">
<asp:ContentPlaceHolder ID="MainContent" runat="server"></asp:ContentPlaceHolder>
</div><!-- /content -->
<div data-role="footer" data-position="fixed" data-theme="b">
<asp:ContentPlaceHolder ID="FooterContent" runat="server"></asp:ContentPlaceHolder>
<input type="hidden" id="collapse_value" value="false" />
</div><!-- /footer -->
</div><!-- /page -->
//Combined jquery 1.8 and jquery mobile files in one
<script src="Js/JQ_JQM_combined.js" type="text/javascript"></script>
//Makes ajax calls to get data
<script src="Js/UserMobile.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
// disable page transitions
$.mobile.ajaxEnabled = false;
$.mobile.defaultPageTransition = 'none';
});
</script>
<asp:ContentPlaceHolder ID="ScriptContent" runat="server"></asp:ContentPlaceHolder>
</body>
</html>
Even the Home page has the flicker problem, where it renders unstyled and then after a period of time properly styled to jquery mobile..
<%# Page Title="" Language="C#" MasterPageFile="~/Mobile/UserMobile.Master" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="User.Mobile.Home" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="TopHeaderContent" runat="server">
<h1>
Applications</h1>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<div data-role="controlgroup">
My Stuff
Employees
List
</div>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="FooterContent" runat="server">
<div class="lines">
<div class="footerCopyrightContainer">
<div class="footerCopyright">
©2012 NICK ALL RIGHTS RESERVED.</div>
</div>
</div>
</asp:Content>
I changed my code to reflect your fiddle example but am still getting the flicker. But the "period of time where the flicker the unstyled to styled is shorter the user still sees the unstyled page in the mobile browser. Can you take a look fo how I got it setup am I missing something?
$(document).bind("pagecreate", function (event, ui) {
//gets params needed from querystring
arrQrStr = getQueryStringParams();
name = arrQrStr["name"];
id = arrQrStr["id"];
});
$(document).delegate('div[data-role=page]', 'pagebeforeshow', function (e, data) {
var employees = null;
//returns string of html needed
employees = getData(name, id);
$('.myBodyContent', this).html(employees);
$(this).trigger('create');
});
getData ajax call..
$.ajax({
type: "POST",
url: "MobileService.svc/REST/GetData",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ id: id}),
dataType: "json",
async: false,
success: function (msg) {
The problem has comes from this:
<script type="text/javascript">
$(document).ready(function () {
// disable page transitions
$.mobile.ajaxEnabled = false;
$.mobile.defaultPageTransition = 'none';
});
</script>
If I take this out of the master page the flicker goes away, it navigates a page fine but the data will not show. Taking this script out breaks the ajax calls and jquery mobile events dont engage (I am not sure why)
It sounds like you misunderstood how the ajax enabled settings works.
By default this setting is enabled and when you link to another page JQM pulls in the the first JQM page that it finds (data-role="page") on the linked page (so you can't link to a multipage document) and enhances it (initializing all the JQM widgets) and then attaches it to the DOM of the current page. When JQM does this it only pulls in the JQM page and nothing else on that page (so any scripts and styling on the second page won't have any effect). The way to deal with this is to have all your scripts in the current main page. One thing you will need to look out for if you do this is that you might end up with multiple pages with the same id (actually with your current setup you definitely will have duplicate ids) so you might want to select them by class instead.
With ajax enabled set to false on the other hand it behaves like a regular link in which case the full page is loaded and if your JQM scripts are on the bottom then then until it's loaded it won't be able to enhance the DOM which is why you are seeing that flicker.
As a side point page transistions are only available ifajax enabledis set totrue`.
To sum up, unless you have a reason not to you probablly should go with ajax enabled set to true, and inlcude the relevant scripts on your main page. If you need to go with ajax enabled set to false then try placing your jQuery scripts in the header so that they load before the rest of the DOM.
Alternaticely what you can do is hide the container element where you will be appending you html and then once your done display it, for example
CSS
.displayNone { display: none; }
HTML
<div data-role="content" class="myBodyContent displayNone">
<asp:ContentPlaceHolder ID="MainContent" runat="server"></asp:ContentPlaceHolder>
</div>
JS
$('.myBodyContent', this).html(employees);
$(this).trigger('create');
$('.myBodyContent', this).reomveClass('displayNone');
Try putting your jquery mobile source scripts in the head, instead of at the end of the body.
This is the only way I could guarantee that the user never sees unstyled html.
Try using the pagebeforeshow instead of pagechange. Like so:
$(document).delegate('div[data-role=page]', 'pagebeforeshow', function(e, data){
var toPage = this; // this references the page that is about to be shown
// Add items to the page
});
The pagebeforeshow event is triggered on the "toPage" being transisioned to, before the actual transition animation starts. This allows you to add in elements and styles before it is displayed to the user.
I hope this helps!
EDIT
Here is a JSFiddle with the suggested fix implemented.
I'm getting more into jQuery and so have set up a HTML/Javascript/CSS base site which I use for all my tests.
Since these tests will eventually turn into PHP and ASP.NET MVC websites, I want to use this opportunity to get the basics down right again for modern browsers and web standards before building the scripting languages on top of it.
I've selected to use:
XHTML 1.0 Strict
UTF-8 encoding
as few CSS references as possible (put everything in 1 CSS file for loading speed)
as few Javascript references as possible (1 javascript file plus the jquery code base reference - I assume using the Google jQuery code base is best practice for speed)
I check my code as I build it with the http://validator.w3.org
Is there anything else I need to consider?
Here is an example of one of my test websites:
index.htm:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<title>Text XHTML Page</title>
<link href="css/main.css" rel="stylesheet" type="text/css" media="all"/>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="javascript/main.js"></script>
</head>
<body>
<h1 class="highlightTitle">Text</h1>
<p class="main">First</p>
<p>Second</p>
<p id="selected" class="regular">Third</p>
<p>Fourth</p>
<form action="">
<div>
<input type="button" value="highlight it" onclick="highlightIt();countThem()" />
<input type="button" value="highlight title" onclick="highlightTitle()" />
<p>here is another paragraph</p>
</div>
</form>
</body>
</html>
main.cs:
p.highlighted {
background-color:orange;
}
h1.highlightTitle {
background-color:yellow;
}
h1.deselected {
background-color:#eee;
}
p.regular {
font-weight: bold;
}
main.js:
google.load("jquery", "1.3.2");
function highlightIt() {
$('#selected')
.toggleClass('highlighted');
}
function countThem() {
alert("there are " + $("p.main").size() + " paragraphs");
}
function highlightTitle() {
$("h1").toggleClass("deselected");
}
Personally I would bind to the click event via jQuery to ensure nice separation, like this:
$("#yourId").bind("click", highlightIt);
This way you can bind to multiple event handlers. If you just use onclick AFAIK you can only ever use one handler.
BTW you can also use custom event and event namespaces:
$("#yourId").bind("beforeHighlighting", doSomething);
is triggered by
$("#yourId").trigger("beforeHighlighting");
and
$(".hasAHelptext").bind("helptext.click", showHelptextFct);
$(".hasAHelptext").bind("click", otherFct);
// will only remove the showHelptextFct event handler
$(".hasAHelptext").unbind("helptext.click");
HTH
Alex
Move the <script> blocks to the bottom of the page.
With regard to CSS and JS files in general, I wouldn't combine all JS files to a single file during development. It gets very hard to develop in one big JS file. Rather use a module that combines them on-the-fly or during deployment.
I usually go with (both CSS and JS):
one general file:
project.css
and one per page:
project_welcome.css
and any special components (login controls, ad area views etc) have a seperate one as well.
That way you can apply some organizing techniques and won't go crazy managing that single large file.
HTH
Alex
I would recommend putting the JS calls below the body tag. If your scripts are hanging, then the page can load and let the behavior (JS) load after the fact. I've noticed that speed greatly improves with this method.
Check this out: http://stevesouders.com/hpws/rule-js-bottom.php