Maintain Scroll position after div.toggle (JQUERY) - javascript

How do I maintain my page scroll position after JQUERY toggle event, I have searched and researched but couldn't find any solution to remedy this problem.
<script src="Scripts/_hideShowDiv/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#adddriverpanel').hide();
$('a#adddrivertrigger').click(function () {
$('#adddriverpanel').toggle(400);
});
});
</script>

After reviewing your code, you simply need to update your html to the following:
<a id="adddrivertrigger" href="javascript:void(0);" class="auto-style2">Add Drivers</a>
The '#' you had in the link is what is taking you to the top of the page.
If you're going to use an anchor tag with an href for a click event, you need to prevent the href from firing (assuming you don't want it to). You can usually do this with adding
return false;
To your click event, but better practice for empty href attributes is to create a null javascript call as opposed to a '#'.
For giggles, here are some other things you should /not/ do with href attributes:
All of the above are either invalid javascript or pose inconsistency problems with different browsers.
Another way you could have solved it (via jQuery) is as follows:
$('a#adddrivertrigger').click(function () {
$('#adddriverpanel').toggle(400);
return false;
});

Related

NivoSlider - Disable Right Click

I have been asked to put in place disabling of the right clicks on a website, I've informed them there is so many ways that people can still download the images via Google Images, Cache, Firebug etc etc, but none the less my arguments have gone ignored and they insist this must be done.
Any, I've put in the footer some code that disables right clicking on all elements using <IMG src=""> this fails to work on NivoSlider, I did change the script to use window load on disabling the right click which works but after slide1 it stops working and I assume this is something to do with changes to the DOM.
JavaScript is by far my weakest point and I'm hoping that someone without to much trouble can either give me a full working solution or something to go on. Thanks in Advance.
They are using NivoSlider with the following trigger:
<script type="text/javascript">
(function($) {
$(window).load(function() {
$('#slider').nivoSlider();
});
})(jQuery);
</script>
And this is the code that I've placed in the footer that fails to work on slide2+
<script>
$(window).load(function() {
$('img').bind('contextmenu', function(e) {
return false;
});
});
</script>
You're absolutely right with the DOM changes. You need to delegate the event to a parent element.
Try something like this:
$('#slider').delegate('img', 'contextmenu', function(e) {
return false;
});
Or this if using jQuery > 1.7:
$('#slider').on('contextmenu', 'img', function(e) {
return false;
});
You might be able to do it by preventing the default behaviour of a right click on the image.
See this answer: How to distinguish between left and right mouse click with jQuery

How to get Anchor Links to work in Jquery Mobile?

Jquery Mobile has decided to treat anchor links as page requests of sort. However, this isn't good if you have a load of blog posts which have anchor links to the same page (ie href="#specs").
Is there a way to disable jquery mobile's anchor link usage on a specific page which I know I won't be using it on so I can use anchor links as they were intended, to drop down to a part of the page?
I only need a solution for anchor links on the same page (ie: href="#specs").
thanks
You could try adding a data-ajax="false" on the anchor tag.
Linking without Ajax
Links that point to other domains or that have rel="external",
data-ajax="false" or target attributes will not be loaded with Ajax.
Instead, these links will cause a full page refresh with no animated
transition. Both attributes (rel="external" and data-ajax="false")
have the same effect, but a different semantic meaning: rel="external"
should be used when linking to another site or domain, while
data-ajax="false" is useful for simply opting a page within your
domain from being loaded via Ajax. Because of security restrictions,
the framework always opts links to external domains out of the Ajax
behavior.
Reference - http://jquerymobile.com/demos/1.0.1/docs/pages/page-links.html
If you are like me, converting an existing site and you don't want to go through every page right now. You can add one line of code to your header and all of your header and all of your existing internal anchor links will get the data-ajax="false" tag added.
Of course, this assumes you are including your own javascript file up in the header already. If you are not you would have to touch every page anyway. But I have a single javascript file that is included in every page already so I added this line...
$("a").each(function () { if(this.href.indexOf("#")>=0) $(this).attr("data-ajax",false); });
This goes in your $(document).ready() block. If you don't have that block yet, here is the entire block.
$(document).ready(function() {
$("a").each(function () { if(this.href.indexOf("#")>=0) $(this).attr("data-ajax",false); });
});
Hope this helps. It is the same solution user700284 offers but in an automated way.
You can add the following code to the end of your page:
<script type="text/javascript">
$('a.native-anchor').bind('click', function(ev) {
var target = $( $(this).attr('href') ).get(0).offsetTop;
$.mobile.silentScroll(target);
return false;
});
</script>
And add the class "native-anchor" to your anchor links.
It is not a total sollution, because the back button of your browser will move you to the previous page and not to the position of the link, but it is better than the links not working at all.
I found this sollution here: jQuery Mobile Anchor Linking
$(document).bind("mobileinit", function () {
$.mobile.ajaxEnabled = false;
});
First you have to place this code into a custom.js file
$(document).bind('mobileinit', function () {
$.mobile.loader.prototype.options.disabled = true;
$.mobile.ajaxEnabled = false;
$.mobile.linkBindingEnabled = false;
$.mobile.loadingMessage = false;
});
Then add this file into your webpage before the jquery mobile js is loaded. becuase 'mobilinit' event is triggered immediately
Thank you
this solution worked for me
<script>
$(document).ready(function() {
$("a").each(function() {
if (this.href.indexOf("index.php") >= 0) $(this).attr("data-ajax", false);
});
});
</script>
I replaced # with index.php which is my document root.
But, it doesn't work for form button i.e input type="submit"
// On page load on mobiles only, look for the specific a tag you want to take control over,
// alternatively you can still target all 'a' tags
$('a[href*="#component"]').each(function () {
// then set data-ajax to false,
$(this).attr("data-ajax", false);
// at this point you can add the class to your target a tags.
// You can do it elsewhere but because for this example my
// 'a' tags are automatically generated so I just add the class here
$(this).addClass('in-pagelink');
// then target the class and bind to a click event
$('a.in-pagelink').bind('click', function (ev) {
// here I redirect the page with window.location.assign
// as opposed to window.location.href. I find that it works better
window.location.assign(this.href);
// then I close my navigation menu
closeAll();
});
});

jQuery slow reveal on page load

I am trying to do a slow reveal on a particular div with an id of 'contentblock' on page load. This is my first time trying to code something in jQuery and I continue to fail. The following is my latest attempt, but I'm a complete newbie to this and surprisingly google hasn't been a whole lot of help.
<script type='text/javascript'>
$(window).onload(function(){
$('#contentblock').slideDown('slow');
return false;
});
</script>
before that I also had the following instead of the window onload line above:
$(document).ready(function(){
But that didn't have any success either. Can someone help a jQuery newbie out?
First, you'll need to make sure the element is hidden (or it won't be shown, since it's already visible). You can do this in either CSS or JavaScript/jQuery:
#contentblock {
display: none;
}
Or:
$('#contentblock').hide();
If you use CSS to hide the element you need to be aware that the element will remain hidden in the event of JavaScript being disabled in the user's browser. If you use JavaScript there's the problem that the element will likely flicker as it's first shown and then hidden.
And then call:
$(window).load(function(){
$('#contentblock').slideDown('slow');
});
I've made two amendments to your jQuery, first I've changed onload to load and I've also removed the return false, since the load() method doesn't expect any value to be returned it serves no purpose herein.
For the above jQuery you can use instead:
$(document).ready(function(){
$('#contentblock').slideDown('slow');
});
$(document).ready(function(){
if($('#contentblock').is(':hidden'))
{
$('#contentblock').slideDown('slow');
}
});
if you have jquery added to your project and your div is display none ... something like this should work.

Executing JavaScript when a link is clicked

Which is preferable, assuming we don't care about people who don't have JavaScript enabled?
Or
Is there any difference?
Or there any other ways I'm missing besides attaching an event to the anchor element with a JavaScript library?
The nice thing about onclick is you can have the link gracefully handle browsers with javascript disabled.
For example, the photo link below will work whether or not javascript is enabled in the browser:
foobar
it's better to use the onclick because that's the way the things should be.
The javascript: was somekind of hackish way to simulate the onclick.
Also I advice you to do some non intrusive Javascript as much as possible, it make the code more easy to read and more maintainable!
href="#" has a number of bad side effects such as showing # in the browser footer as the destination URL, and if the user has javascript disabled it will add a # at the end of their URL when they click the link.
The best method IMHO is to attach the handler to the link in your code, and not in the HTML.
var e = document.getElementById("#myLink");
e.onclick = executeSomething;
This is essentially the pattern you'd want to follow:
Write your HTML markup
Attach event handlers from JavaScript
This is one way:
<a id="link1" href="#">Something</a>
<script type="text/javascript">
// get a reference to the A element
var link1 = document.getElementById("link1");
// attach event
link1.onclick = function(e) { return myHandler(e); };
// your handler
function myHandler(e) {
// do whatever
// prevent execution of the a href
return false;
}
</script>
Others have mentioned jQuery, which is much more robust and cross-browser compatible.
Best practice would be to completely separate your javascript from your mark up. Here's an example using jQuery.
<script type="text/javascript">
$(function() {
$('a#someLink').click( function() {
doSomething();
return false;
});
});
</script>
...
some text
Yes I would agree to use onclick and leave the href completely out of the anchor tag... Don't know which you prefer to do but I like to keep the 'return false' statement inside by function as well.
The main difference is that:
The browser assume by default the href attribute is a string (target url)
The browser knows that in a onclick attribute this is some javascript
That's why some guys specify to the browser "hey, interpret javascript when you read the href attribute for this hyperlink" by doing ...
To answer the question, that's the difference!
OTOH what's the best practice when using javascript events is another story, but most of the points have been made by others here!
Thanks

JavaScript: changing the value of onclick with or without jQuery

I'd like to change the value of the onclick attribute on an anchor. I want to set it to a new string that contains JavaScript. (That string is provided to the client-side JavaScript code by the server, and it can contains whatever you can put in the onclick attribute in HTML.) Here are a few things I tried:
Using jQuery attr("onclick", js) doesn't work with both Firefox and IE6/7.
Using setAttribute("onclick", js) works with Firefox and IE8, but not IE6/7.
Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return is code passed to eval().
Anyone has a suggestion on to set the onclick attribute to to make this work for Firefox and IE 6/7/8? Also see below the code I used to test this.
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var js = "alert('B'); return false;";
// Set with JQuery: doesn't work
$("a").attr("onclick", js);
// Set with setAttribute(): at least works with Firefox
//document.getElementById("anchor").setAttribute("onclick", js);
});
</script>
</head>
<body>
Click
</body>
</html>
You shouldn't be using onClick any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()
$(document).ready(function(){
var js = "alert('B:' + this.id); return false;";
// create a function from the "js" string
var newclick = new Function(js);
// clears onclick then sets click using jQuery
$("#anchor").attr('onclick', '').click(newclick);
});
That should cancel the onClick function - and keep your "javascript from a string" as well.
The best thing to do would be to remove the onclick="" from the <a> element in the HTML code and switch to using the Unobtrusive method of binding an event to click.
You also said:
Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return in code passed to eval().
No - it won't, but onclick = eval("(function(){"+js+"})"); will wrap the 'js' variable in a function enclosure. onclick = new Function(js); works as well and is a little cleaner to read. (note the capital F) -- see documentation on Function() constructors
BTW, without JQuery this could also be done, but obviously it's pretty ugly as it only considers IE/non-IE:
if(isie)
tmpobject.setAttribute('onclick',(new Function(tmp.nextSibling.getAttributeNode('onclick').value)));
else
$(tmpobject).attr('onclick',tmp.nextSibling.attributes[0].value); //this even supposes index
Anyway, just so that people have an overall idea of what can be done, as I'm sure many have stumbled upon this annoyance.
One gotcha with Jquery is that the click function do not acknowledge the hand coded onclick from the html.
So, you pretty much have to choose. Set up all your handlers in the init function or all of them in html.
The click event in JQuery is the click function $("myelt").click (function ....).
just use jQuery bind method !jquery-selector!.bind('event', !fn!);
See here for more about events in jQuery
If you don't want to actually navigate to a new page you can also have your anchor somewhere on the page like this.
<a id="the_anchor" href="">
And then to assign your string of JavaScript to the the onclick of the anchor, put this somewhere else (i.e. the header, later in the body, whatever):
<script>
var js = "alert('I am your string of JavaScript');"; // js is your string of script
document.getElementById('the_anchor').href = 'javascript:' + js;
</script>
If you have all of this info on the server before sending out the page, then you could also simply place the JavaScript directly in the href attribute of the anchor like so:
Click me
Note that following gnarf's idea you can also do:
var js = "alert('B:' + this.id); return false;";<br/>
var newclick = eval("(function(){"+js+"});");<br/>
$("a").get(0).onclick = newclick;
That will set the onclick without triggering the event (had the same problem here and it took me some time to find out).
Came up with a quick and dirty fix to this. Just used <select onchange='this.options[this.selectedIndex].onclick();> <option onclick='alert("hello world")' ></option> </select>
Hope this helps

Categories

Resources