javascript use for getting element - javascript

<li class="even">
Click here
</li>
I want to change anchor tag text "Click here" using javascript. How can i accomplish this ?

If you're not constrained to using that exact markup and you're really looking for one of the best ways to do this, start off by giving a unique Id to the element that you're going to change:
Click here
document.getElementById("mylink") will give you that element.
Before manipulating an element on the page, you need to ensure that the document is loaded and ready for manipulation. Avoid using inline JavaScript in attributes. Use the following method to attach a document load handler:
window.onload = function () {
// manipulate the document here
};
So, what you're looking for would be:
window.onload = function () {
document.getElementById("mylink").innerHTML = "Something Else";
};
But, if you're really looking for a better solution, don't hesitate to enter the realm of jQuery:
$(function () {
$("#mylink").html("Something Else");
});

document.getElementsByTagName("a")[0].innerHTML = "Changed click here"; //0 is assuming this is your only link
It'd be better to use an id to access that particular link.
EDIT: I noticed you want this to happen on page load:
<body onload="document.getElementsbyTagName('a')[0].innerHTML = 'Changed text';">
Or you could placed that code in a function somewhere and call the function instead.

<body onload="document.getElementById('mylink').innerHTML='new text';">
<li class="even">
<a id='mylink' href="www.google.com">Click here </a>
</li>
</body>

Related

Right way of triggering a javascript from html

What is the way for having a graphical component (more precisely a twitter.bootstrap icon) in an html website calling a java script.
One could either make a button and putting the icon on it, but this does not look nice IMHO.
Or one could use the href tag,
<a href="#" name="ad_fav" onclick= CALLFUNCTION> <i
class="icon"></i></a>
But what is the cleanest way of achieving this?
It would also be nice if the icon could change after it was clicked.
How it for example the upvote button in stackoverflow implemented?
Another way:
function myFunc () {
// code here
}
var element = document.getElementsByClassName("icon");
element[0].addEventListener("click", myFunc);
Just make the href of the <a> be 'javascript:', example:
<a href="javascript:alert('hello there! this works!')" name="ad_fav"> <i
class="icon"></i></a>
Replace alert(...) with your function call if you need
You don't have do wrap it with an anchor element:
<img src="[path to twitter.bootstrap icon]" onclick="yourJavaScriptFunction" />
Why wouldn't you use jquery on function?
$(document).on("click", "a.icon", function (e) {
e.preventDefault();
});

how to add a css class in javascript to be used onload

I am trying to load a popup lightbox window when the page is initially opened. I can get it to work on a click but I cannot get the code right to add a class in the script. I am using 'Lightbox' from within HTML Kickstart.
The link that works looks like this: <a class="lightbox" href="#bbc">BBC</a> This works perfectly. Basically how do I get that to work automatically on page load.
My attempt at the script:
<script type="text/javascript">
function load() {
var target = location.href = "#bbc";
target.className = "lightbox";
}
</script>
So I assume you want to add a class to that anchor tag:
$(function () {
$("a[href=#bbc]").addClass("lightbox");
});
Using $(function() {…}) is the same as using the ready() function (in JQuery). I would recommend running the code after the DOM is ready rather the "on load".
you need to call the load() function on the onLoad event of <body> tag.
<body onLoad="load()">
The way I read this question — ignoring the title — is that the user is trying to trigger the lightbox on load. Whilst this may be a wrong assumption, the way to trigger a link using javascript is to use the .click() method:
window.onload = function(){
var i, list = document.getElementsByTagName('a');
for ( i=0; i<list.length; i++ ) {
/// this will only work for links with only a class name of lightbox.
/// you could look into using getElementsByClassName or something similar.
/// I use getElementsByTagName because I know how supported it is.
if ( list[i].className == 'lightbox' ) {
list[i].click();
}
}
};
The above code would support multiple lightbox links in a page, which might not be desired, so it may be best just to add an id to the link you wish to target and then use:
window.onload = function(){
document.getElementById('clickonload').click();
};
<a id="clickonload" class="lightbox" href="#bbc">BBC</a>
You may find however, that in reading the documentation for whatever lightbox plugin you are using, that there is a command you can use from JavaScript, rather than clicking a target link.
$(window).load(function () {
var target = location.href = "#bbc";
target.className = "lightbox";
});

Run JavaScript function on element defined with jQuery

Not sure I titled this well.. show's that I'm in unfamiliar territory. How can I run a JavaScript function based off of the element called in a jQuery function?
Theory:
<script type="text/javascript">
$.fillit('video');
</script>
(run fillit on video tag present in page.. interchangable with other elements)
$.fillit = function(){
this is where it says "run on the tag defined in the jQuery function"
}):
$.fn.extend({
fillit : function(){...}
});
then...
$('.video').fillit();
Edit (after comments)
To fill a dom element with other elements/html:
var img = document.createElement('img');
img.setAttribute('src', 'somesrc.jpg');
$('.video').append(img);
or
$('.video').html('<img src="somesrc.jpg"/>');
You can do it the way you described like so
<script type="text/javascript" language="javascript">
$.fillit = function(content)
{
$("result").html(content);
}
//call function
$.fillit("HELLO WORLD");
</script>
or as Alexander just posted if you want to do it on the selected element.
I don't think adding functions directly to jquery with $.func = is a good idea though. If jQuery ever adds a fillit method your method will conflict with theirs.
technopeasant, it sounds like you are using a jquery plugin (in your example, a plugin called 'fillit') and it is asking you to run the plugin on a tag or series of tags. Sorry if I misunderstood your question.
If that is the case, all you need to do is one of two things. If you are trying to run it on a very specific element in the HTML page (one with an id like <div id="myvideo"></div>) then all you need to do is run:
$('#myvideo').fillit();
//Notice the '#' symbol, that looks up the element with an id of 'myvideo'
If you want to run the plugin on a series of elements (like all <p> tags in the entire document, you'd run something like:
$('p').fillit()
//notice no '#', it's just looking up all <p> tags regardless of ID.
Take a look at the jQuery documentation regarding selectors to get a more concrete idea of how these selectors work:
http://docs.jquery.com/How_jQuery_Works
Someone answered with a link to this: http://docs.jquery.com/Plugins/Authoring
exactly what I was looking for. claim your kudos!
(function( $ ){
$.fn.fillit = function() {
this.fadeIn('normal', function(){
var container = $("<div />").attr("id", "filled")
.appendTo(container);
});
};
})( jQuery );

Ajax inserted content not accessible in DOM

I am working on a pure jquery/js site, mostly to practice some jquery. I am using a load statement to load a menu from a file of common html, like so:
$('#categoryListing').load('../common.html #categoryLinksUL');
which loads:
<ul id="categoryLinksUL">
<li>Anklets</li>
<li>Bracelets</li>
</ul>
The problem is where I am using it now I need to alter the href of the above links, but they are not part of the dom. In previous instances I was able to use .live(click... But not here. Is there a way I can accomplish this?
Specifically I need to load the links and change the href from #anklets to ?category=anklets
What about the following?
$('#categoryListing').load('../common.html #categoryLinksUL', function() {
$('li a[href^="#"']').each(function () {
this.href = '?category=' + this.href.substr(1);
});
});
In my example, after the load is completed, the anonymous function is called. It takes every anchor with a hash HREF and replaces it with an HREF based on your description.
Thank you Dimitry, you solution basically worked. I finally used:
$('#categoryListing').load('../common.html #categoryLinksUL', function() {
$('#categoryListing li a').each(function () {
var hashPos=this.href.indexOf("#");
var tCategory = this.href.substr(hashPos+1,this.href.length );
});
});
So why did jQuery recognize categoryListing there? I tried moving the each function outside of the load function and categoryListing did not contain any links. Is it because maybe the load was not completed when it tried to get categoryListing links? Seems like that is possible.
Thanks,
Todd

how to stop # links that call javascript functions from jumping to top of page

How do you I stop my links like this:
<a href="#" onClick="submitComment()">
From jumping to the top of the page after the click?
Many times you'll see people use the onclick attribute, and simply return false at the end of it. While this does work reliably, it's a bit ugly and may make your code-base difficult to manage.
<a href="#" onClick="submitComment(); return false;">
Seperate your HTML from your JavaScript
It's far better for you, and your project if you separate your markup from your scripting.
<a id="submit" href="enableScripts.html">Post Comment</a>
With the above HTML, we can find this element and wire up a handler for when the user clicks on the element. We can do all of this from an external .js file so that our HTML remains nice and clean, free from any scripting:
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", setup, false);
} else if (document.attachEvent) {
document.attachEvent("onreadystatechange", setup);
} else {
document.onload = setup;
}
function setup () {
var submit, submitComment;
submit = document.getElementById("submit");
submitComment = function (e) {
e = e || window.event;
e.preventDefault();
alert("You clicked the link!");
};
if (submit.addEventListener) {
submit.addEventListener("click", submitComment, false);
} else if (submit.attachEvent) {
submit.attachEvent("onclick", submitComment);
} else {
submit["onclick"] = submitComment;
}
}
There's a lot going on in the above code, but let's run over it from 30,000 feet. We start by figuring out how to best setup our code when the browser loads the page up. Ideally we'd like to do this when the DOM is ready.
After a few conditional checks we manage to instruct the browser to run our function after the DOM is prepared (this way our anchor element exists for us to interact with its behavior).
Our setup function gets a reference to this anchor, creates a function that we'll run when the anchor is clicked, and then finds a way to attach that function call to the click event of the anchor - losing your mind yet? This is the madness JavaScript developers have had to deal with for some time now.
With jQuery, this is much easier
Perhaps you've heard of jQuery, and wondered why it is so popular. Let's solve the same problem, but this time with jQuery rather than raw vanilla JavaScript. Assuming the following markup:
<a id="submit" href="enableScripts.html">Post Comment</a>
The only JavaScript we need (thanks to jQuery) is this:
$(function(){
$("#submit").on("click", function(event){
event.preventDefault();
submitComment();
});
});
That's it - that is all it takes. jQuery handles all of the tests to determine, given your browser, what the best way is to do this or that. It takes all of the complicated stuff and moves it out of the way so that you are free to be creative.
Add a return false. I believe that without that the page will reload.
<a href="#" onClick="submitComment(); return false;">
Just return false onClick of Hyperlink
Its will not scroll page up ie it will be still where it is
Unless you need the anchor to actual go somewhere, you don't need to use an "href=" reference at all.
Try just using <a id="stay-put">Submit Comment</a>
Then your javascript would look like this:
$("#stay-put").click(function(){
submitComment();
});
Try using:
Javascript is sweet!
This will anchor the page in the place it is at. I had this same issue and this was a simple and good fix for me.
An other simple way is
Link
Then you could have a separate code with onClick event to the class "action-class" with whatever framework you like or plain JavaScript.
You could use this alternative syntax instead:
<a href="javascript:submitComment()">

Categories