Javascript help, toggle text keeps jumping back to top of page - javascript

I hope someone can help with this issue, I've tried many scripts and workarounds, but can't get this simple thing to work. As the title has it, how can I make my text NOT jump to the top of the page. Here is the code:
<script type="text/javascript">
function toggleVisibility() {
document.getElementById("toggleMe").style.display = "";
if(document.getElementById("toggleMe").style.visibility == "hidden" ) {
document.getElementById("toggleMe").style.visibility = "visible";
}
else {
document.getElementById("toggleMe").style.visibility = "hidden";
ev.preventDefault();
return false;
}
}
</script>
Click to toggle visibility.</p>
<div id="toggleMe" style="visibility: hidden;"> Something to Hide and show.
Display collapses it's layout while visibility will keep it's layout.
All in the same html file. I read what outhers did and I tried the
ev.preventDefault();
return false;
code at the end of the function, but nothing.

Change the href attribute in the A tag to: javascript:; instead of #
So use this to create your javascript enabled anchor:
<a href="javascript:;">
added (background info):
The # character indicates a bookmark. By omitting the name of the bookmark e.g. #bottom the browser considers the bookmark as 'top of the page' thus scrolling to the top. Your problem does not have to do anything with bookmarks, however using # to define an empty link for a javascript enabling anchor (A) tags is not the way to go. You should use: javascript:; or javascript:void(0); to indicate that this is not a navigation anchor.

Or simply always return false, not just in the Else clause.

Related

href and js to be worked work together on html

I am trying to open my href link and setting the padding of container of web page at same time.
My code is as
<a href="/Link1/" onclick="return SizeOf(); " >LinkText</a>
function SizeOf() {
document.getElementById("contain1").style.padding = "000px 150px 00px 210px";
}
But for now either of them working.Either I can open my page or I can set the paddings using CSS.I want to do the both things i.e. open my page and set padding as well.
Please help me with this.
Thanks
I encountered the same problem before. The way I deal with it is to put the href stuff inside the function as well, otherwise the click can only trigger either href or the function.
Please try the following, or similar:
LinkText
function SizeOf() {
document.getElementById("contain1").style.padding = "...";
window.location.href = '/Link1/';
}
Use mousedown it will trigger before redirect the link.so both thing's will append
function SizeOf() {
document.getElementById("contain1").style.padding = "000px 150px 00px 210px";
}
<a href="/Link1/" onmousedown="SizeOf() " target="_top" >LinkText</a>
<p id="contain1">contain</p>

how to call or display a div by changing url using href?

i am trying to show a div which is currently hide and inside body tag.by changing url using anchor tag attribute href.Like below---
<a id="ai" href="managevendors" class="tablink" onclick="openCity()">Manage Vendors
</a>
<div class="w3-container city" style="display: none;" id="managevendors">
<h1>hi,how are you</h1>
</div>
when i click on this anchor tag my url will definitely changed.and based on url i wants to display a div.
my js code...
function openCity() {
if (window.location.hash == "managevendors") {
$("#managevendors").show();
}
}
i dont know why this is not working.but i teide with different way like below..
<a id="ai" href="#managevendors" class="tablink" onclick="openCity('managevendors')">Manage Vendors
</a>
and js code.....
function openCity()
{
if (window.location.hash == "#managevendors") {
$("#managevendors").show();
}
}
but i dont want the # sing,how can i solve it.help me experience brothers.thanks in advance.
You must use the hash if you expect the navigation to work. Once you do that, you don't need to check for it, you can just show the section:
$("#ai").on("click", openCity);
function openCity() {
// The only reason this code is running is because the link was clicked.
// No need to test for it.
$("#managevendors").show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- You have to include the hash in the href for navigation to work -->
<a id="ai" href="#managevendors" class="tablink">Manage Vendors
</a>
<div class="w3-container city" style="display: none;" id="managevendors">
<h1>hi,how are you</h1>
</div>
I think the problem here is that you are using an anchor tag when you should be using a button. The reason the first way is not working is due to the page refreshing when you click the link.
Try changing your <a> to a <button>
From what I understand, you most likely need the href="#xyz" with a hash. This will keep clientside logic active without trying to solve the url and take a detour to the server for nothing. If you're going to capture that part, keep it local.
I suggest to remove the onclick handler from HTML. To capture the link you can use jQuery to keep your HTML "clean". If you must, for some odd reason, by all means you can reference onclick="openCity(this)", so the element you click on is passed directly to openCity.
// vanilla
function openCity(element){
var href = element.getAttribute('href'), // expecting a hash here
id = href.substr(1), // remove the hash
target = document.getElementById(id);
target.className += " active";
return false;
}
As Scott suggests with jQuery:
//$('.tablink').on('click', openCity);
$('.tablink[href^="#"]').on('click', openCity);
Then the function can be made dynamic by referencing the href from the clicked element:
function openCity(ev){
var el = $(ev.currentTarget),
id = el.prop('href'), // expecting a hash here
target = $(id);
// since you're providing both with and without hash, the default behaviour is to follow the link, unless referenced with a hash
ev.preventDefault();
target.addClass('active');
}
If the id was not found on the page, this will void silently.
Now if you want to work with the url as entry point, note that this will only happen on load event => share a link and someone clicks on it (with the #xyz attached) or type directly in the address bar.
// 1. bind the event
$(window).load(function(){
/*loadCity defined here or outside*/
loadCity();
});
// 2. define what happens
function loadCity(){
var id = window.location.hash, // expecting a hash here
target = $(id);
target.addClass('active');
}
Since this solution only solves state of an element, the actual show/hide part can be made in CSS. Very simple as you probably already did or with animations, transitions and so on.
.city { display: none; }
.city.active { display: block; }

jQuery Hide/Show DIV on change of anchor text

I have one page website which changes URL #id or anchor text on scrolling and on navigation click. I have an image positioned fixed at the center of the site. The site is divided in different sections and the image shows in all the sections. I do not want to show the image on the first section as it is unrelated to the content of the 1st section but will be showed in all next sections. How can I make it work?
What I have tried till now but not working:
$(document).ready(function(){
$(".phone").hide();
var idSample = window.location.href.split("#");
var id = "#"+idSample[1];
if($(id) == "second"){
$(".phone").show();
}else{
$(".phone").hide();
}
});
Rest in Fiddle: https://jsfiddle.net/shubhamjha1000/vh7bu32q/
I don't want that phone to be seen on 1st section but on rest of the sections. Please help me guys!
You can use the answer written in this question to listen to changes in the window see what url you are on and show or hide the phone accordingly....
Example:
$(function(){
// Bind the event.
$(window).hashchange(hashchanged);
// Trigger the event (useful on page load).
hashchanged();
});
function hashchanged(){
var hash = location.hash.replace( /^#/, '' );
//your code
if(hash == "#first") {
// Hide element
} else {
// Show element
}
}
But still even though what you are planning to do will work with that solution I think it would still look bad on the app it self and instead of a hovering phone maybe you can create the phone as an img inside the relevant containers and hide and show with id...
You can simply use a substring on your location.hash for get your hash tag
$(document).ready(function(){
$(".phone").hide();
var id = window.location.hash.substr(1);
if($(id) == "second"){
$(".phone").show();
}else{
$(".phone").hide();
}
});

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();
});
});

How to disable user's input while loading page with jQuery?

I have a heavy-jquerized page with some links, various user inputs and such.
I use jquery, with actions defined in a
$(document).ready( function() {
....
} );
block.
But while the page is loading (or, even worse - reloading), and a user clicks a link, the href action from it is triggered, as the javascript isn't loaded / active yet.
I wanted to block it somehow. One way that came to my mind is to put a transparent div over whole document, that would receive the click events instead of the layer below it. Then, in my .ready function in javascript, I could hide that div making it possible to use the page.
Is it a good practice? Or should I try some different approach?
Another option is to use the jQuery BlockUI plugin (which probably usew the same or similar idea behind the scenes).
If you don't want your links to act like links (ie their href is never meant to followed), why make them links in the first place? You'd be better served by making your clickable elements a div or span (something without a default action), and attaching the click handler as per normal.
I'd really advise against blocking the ui with a div - it seems the entirely wrong approach, making the page non-functional to someone with JS disabled, as well as blocking other common tasks like copying text.
In light of the clarification, to block the UI only if JS is enabled, but not yet loaded, I'd suggest the following.
HTML (first thing after body):
<script type="text/javascript">document.write('<div id="UIBlocker">Please wait while we load...</div>')</script>
CSS:
#UIBlocker
{
position: fixed; /* or absolute, for IE6 */
top: 0;
bottom: 0;
left: 0;
right: 0;
}
Or, if you prefer not to use document.write, leave the UIBlocker div as straight HTML at the top of body, but have the following in head
HTML:
<noscript>
<style type="text/css">
#UIBlocker { display: none !important; }
</style>
</noscript>
This will ensure it does not block for non-JS enabled browsers
A transparent div could work, assuming it’s positioned above everything. (I’m never quite clear how visible an element has to be to receive click events.)
You might want to make the div visible though; it could be equally confusing for visitors if they can see everything on the page, but not click it.
You’ll probably need to use JavaScript to make the div as tall as the page though.
The overlay DIV should work. Another option would be to place all the content inside a hidden container visibility: hidden then toggle to visible as the last $(document).ready statement.
As you said it yourself javascript isn't loaded yet. Maybe the css isn't loaded either.
so something with visual element will not work i think. IF you want to do some with the viaual elements (css) you have to hardcode it in the html node <tagname style="blabla">
You could possibly add the href behavious in a later stadium when the js is loaded.
What you get is a <span> with a title and this should set the behaviour or something. I used a title, but can be a different attribute.
This doesn't use any jquery, only for loading
$(document).reade(function () {
relNoFollow();
});
function relNoFollow() {
var FakeLinks = document.getElementsByTagName('span');
if( FakeLinks.length > 0 ) {
for( var i = 0; i < FakeLinks.length; i++ ) {
if( FakeLinks[i].title.indexOf( 'http://' ) != -1 ) {
FakeLinks[i].onmouseout = fakelinkMouseOut;
FakeLinks[i].onmouseover = fakelinkMouseOver;
FakeLinks[i].onclick = fakelinkClick;
}
}
}
}
function fakelinkMouseOver() {
this.className = 'fakelink-hover';
}
function fakelinkMouseOut() {
this.className = 'fakelink';
}
function fakelinkClick() {
window.location.href = this.title;
}

Categories

Resources