I need to add a class (.open) to an element (h2) on another page from the home page depending on which option is clicked.
The jquery below shows a line of code that i've written which although doesn't work gives you an idea of what i'm trying to do.
Jquery
//open service section from home page
var hash = window.location.hash;
if(hash != "") {
var id = hash.substr(1);
document.getElementById(id).style.display = 'block';
//document.getElementById(id).previous('h2').addClass( "open" ); //CODE THAT DOESN'T WORK
}
HTML (This is what i'm trying to ahceive. As you can see the h2 contains the .open tag)
<h2 class="section-heading toggle open">heading title</h2>
<div id="content1" class="slide-content"></div>
</div>
You're mixing up the DOM and jQuery. I suggest using one or the other.
The jQuery way to write the commented out "code that doesn't work" line is
$(hash).prev().first().addClass("open");
or
$(hash).prevAll('h2').first().addClass("open");
...if there's any chance of an element between the one with the ID and the h2.
Note I used hash rather than id, since it has the # on it, and conveniently that's how you select by id in CSS.
Related
Ok, I will try explain my question.
I need to add class ".active" into already existing class ".jobs", when URL have hashtag same as ID, inside tag with class ".jobs".
Here is working code just for one compare:
$(document).ready(function() {
var hashVal = window.location.hash.split("#")[1];
if(hashVal == 'programmer') {
$("#programmer").addClass('active');
}
});
In practice:
Someone will come to website www.domain.tld/jobs#programmer then I need compare "#programmer" from ULR with all existing IDs in all <div> tags, which also have class ".jobs", and if there will be someone with class="jobs" and also id="programmer", I need to add into this <div> tag class "active".
Is there a way to make jQuery code more variable? Like without having add comparison for each ID name? and also I need to move browser windows on position, where div with that ID it is.
var hashVal = window.location.hash.split("#")[1];
if($('#'+hashVal).hasClass('jobs')) $('#'+hashVal).addClass('active');
I'm a JavaScript novice and I'm having some difficulty getting my code to work. I've set up a function that pulls in variables based on element classes and IDs and executes it onclick.
<div id="holder">
<img id="wallImg" src="/testpath/selwall/nopaint.jpg">
</div>
<div id="options">
<ul id="selWall">
<li class="bluepaint" onclick="printStuff()"><strong>Blue</strong></li>
<li class="redpaint" onclick="printStuff()"><strong>Red</strong></li>
<li class="greenpaint" onclick="printStuff()"><strong>Green</strong></li>
</ul>
</div>
<script type="text/javascript">
function printStuff() {
var imgCategory = srcElement.parentNode;
var imgClass = srcElement.className;
document.getElementById("wallImg").src="http://testurl.co.uk/media/gbu0/" + imgCategory + ImgClass + ".png";
}
</script>
The user is supposed to be able to select their paint colour from a selection of swatches (the ul#selWall li elements) and the JS will change the source of a particular image ID on the page (in this case, img#wallImg) with the clicked element's class and clicked element's parent element ID.
Eventually I want to be able to expand this script to use the ul id as a URL parameter name and the paint type (i.e. testurl.com/paint-selection&selWall=bluepaint&selDoor=greenpaint.) As far as I know, JQuery is unable to append URLs so I'd rather stick with plain JavaScript.
You're saying you want to stick with javascript because you don't think jQuery can append URLs. This is not a real reason to just entirely ignore it. JQuery IS javascript, it's just a library. This means that you can just use vanilla javascript whenever you want it, for example, when you want to change the URL.
Now for your desired functionality. You can use the keyword this in your inline click event registrator (i.e. onclick="printstuff()"). Passing the this variable will allow you to use the clicked element in the click handler. So change onclick="printStuff()" to onclick="printStuff(this)". Now in your function you can just use this instead of srcElement, and make sense.
OR INSTEAD USE JQUERY LIKE THE REST OF THE WORLD
$(document).ready(function(event){
$("#selwall).children("li").on("click", function(event) {
event.preventDefault();
var category = "sellwall"; //probably want to store this into a data-category arrtibute somewhere (maybe in the id=sellwall ul)
var imgClass = $(this).attr('class'); //preferably use data-img_id or something too (i.e. dont use classes and id's to store data you need somewhere else).
$("#wallImg").attr('src', <url> with imgClass and category>);
});
})
So I'd recommend using jQuery (since you're a javascript novice too, dont learn bad stuff, just learn how to program well right away) and using the data-attribute paradigm, look it up on the internet. Use it to store the URL parts you want to use.
Made some changes to your script to make script work and get the parent id and class of the current element.
function printStuff(srcElement) {
var imgCategory = srcElement.parentNode;
var imgClass = srcElement.className;
document.getElementById("wallImg").src="http://testurl.co.uk/media/gbu0/" + imgCategory.getAttribute('id') + imgClass + ".png";
alert(document.getElementById("wallImg").src);
var url = 'testurl.com/paint-selection&selWall='+imgClass+'&selDoor='+ imgCategory.getAttribute('id');
alert(url);
}
<div id="holder">
<img id="wallImg" src="/testpath/selwall/nopaint.jpg">
</div>
<div id="options">
<ul id="selWall">
<li class="bluepaint" onclick="printStuff(this)"><strong>Blue</strong></li>
<li class="redpaint" onclick="printStuff(this)"><strong>Red</strong></li>
<li class="greenpaint" onclick="printStuff(this)"><strong>Green</strong></li>
</ul>
</div>
currently I'm trying to make it so that when the user clicks a link it submits the corresponding form via javascript. I used document.getElementById("id").submit() as a basis on how to send the form so my code should act similar to it in my understanding.
Here's the code:
function run(clickedLink){
clickedLink.id.submit(); //I did it like this since document.getElementById just gets the form id and since link and form have similar id's I thought it would send
}
<form id = 'formId'>
<a href = '#' id = 'formId' onclick = run(this)>Link</a>
</form>
I tried going with name = 'formId' too but it still doesn't run as I wanted it too.
Note: doing this since this code iterates dynamically and the id gets updated i.e. formID1, formID2...
Better ways to implement this are welcome too
Modify your function as follows
function run(clickedLink){
clickedLink.parentNode.submit(); // parentNode refers to the form element
}
You cannot use same id on the same page for more than one element. This is against HTML and DOM specifications https://softwareengineering.stackexchange.com/questions/127178/two-html-elements-with-same-id-attribute-how-bad-is-it-really .
You can change it to class if you want to reuse or you can change the id itself of other element. Also links are not recommended to submit the form. Their job is to navigate
Try this:
<a href="#" onclick="document.forms[0].v.value='Link1';
document.forms[0].submit();">Link 1</a>
One Basic thing:
-ID's are used to Uniquely Describe The Element in DOM Hierarchy. Please Don't Repeat it. (it is really bad)
Now to the answer:
function run(x){
var y=findParentForm(x); /* if Id's aren't Unique */
// If iD's are Unique :- var y=document.getElementById("formId");
y.submit();
}
function findParentForm(elem){
/*
This function will find exact parent form
even if link or elem is inside <div> or other complex DOM structure
This will Only return the parent <form> of that elemnt
*/
var parent = elem.parentNode;
if(parent && parent.tagName != 'FORM'){
parent = findParentForm(parent);
}
return parent;
}
<form id='formId' action="Server Side Script" method="GET/POST">
Link <!-- change id of link -->
</form>
I've got the following HTML code, which essentially pertains to a post where I announce something in just a few lines, end it with "[...]", and add a "Read more" link-button at the bottom. When this button is clicked, additional content that's hidden will fadeIn as the button disappears, leaving visible the introductory text and the one that was hidden -- simple enough. Now, I've already written the code for this, but the complication comes when I try to also remove that "[...]" (from the post where the click button happened) that I included in the sneak peek. Here's the HTML:
<div class="entry">
<p>Welcome. Talk about something briefly and click below for more. [...]</p>
<div class="slide-content">
<p>Hidden content.</p>
</div>
<span id="revealer" class="button">Read more</span>
</div>
Classes "entry" and "button" belong to my CSS file, while "slide-content" belongs to my .js file to control the fadeIn effect. The ID "revealer" also belongs to the .js file for the same purpose. This HTML is wrapped in a div tag with a class of "box". This is the format that each post follows, exactly the same format with the same HTML elements -- every time an announcement needs to be made, it's just a matter of putting the content between the paragraph tags and publish. Here is where my problem comes in, since I can't find a way to remove the "[...]" only in the post where the button has been clicked. I tried doing the following but it resulted in the deletion of all "[...]" throughout multiple posts:
$('.entry p').each(function() {
var textReplace = $(this).text();
$(this).text(textReplace.replace('[...]', ''));
});
Summary:
I need to remove the "[...]" text only from the post where the user has clicked on (the "Read more" button). The idea is to have this removed while at the same time the hidden content fades in.
I've been able to accomplish the above but for all instances of "[...]". I need to sophisticate my selection by modifying my jQuery code or the HTML.
Option 3 is to get rid of this "[...]", but I would like to leave it there to let the user know she has more content to read, and I would like to have that "Read more" button in all posts for consistency.
~Thanks in advance!
First, you mention you have multiple of these. In that case, this:
<span id="revealer" class="button">Read more</span>
will not work. id attribute has to be unique per document, i.e. you can have at most one element with the specific id value.
If you make your HTML (for each of the blocks) like this:
<div class="entry">
<p>Welcome. Talk about something briefly and click below for more. [...]</p>
<div class="slide-content">
<p>Hidden content.</p>
</div>
<span class="revealer button">Read more</span>
</div>
and your JS like this:
function replace(fromp) {
var textReplace = fromp.text();
fromp.text(textReplace.replace('[...]', ''));
}
$('.revealer').click(function() {
var fromp = $(this).siblings().eq(0);
replace(fromp);
});
it will work properly. Working example:
http://jsfiddle.net/G4t7Q/
Hope this helps.
When you run your page initialization script, you could use jquery to select all of the posts and all of the remove buttons and link them up via their click event. I've created a JSFiddle example, but here's the jist of it:
var removers = $(".remover")
var posts = $(".post")
for (var i = 0; i < removers.length; i++) {
$(removers[i]).click( { post: posts[i] },
function(event) {
var textReplace = $(event.data.post).text()
$(event.data.post).text(textReplace.replace('[...]', ''))
}
)
}
This is a simplified example; it assumes the posts and buttons are sorted in the markup.
Interesting (and rather complex) issue here...
What I have is a page with two iframes and a set of links at the top, each contained inside a div with an image background. What I want is for the contents of both iframes to change (to two separate html documents) when the link is clicked, and for the background image of the link's parent div to also change. I also, however, want the parent div to automatically change back to the original class when a different link is clicked (i.e. I have two classes, 'active' and 'waiting'. When a link is clicked (and its contents subsequently displayed in the iframes) I want it to switch to class 'active'. At all other times, though, (including after a different link might be clicked and become active) I want it to go back to using the 'waiting' class.)
Here's my current code / markup:
Javascript:
function changeFrame(link) {
$('#first iframe').src=link.href;
$('#second iframe').src= (Here would be the second link, not sure how to define that)
link.ParentNode.addclass("activebutton");
HTML:
<div class="waitingbutton">
<a href="yes.html" (Somewhere here would be the second link for the second iframe) class="waitingbutton" onclick="changeFrame(this);
return false;">Button Text</a>
</div>
(After this come four more divs, each identical bar Button Text and links)
As I suspect you can tell, I'm really just guessing here. Still not hugely familiar with Javascript, hoping someone can help me out.
You seem to be using jQuery.
Here's an ugly way to do it; but it works:
Button Text
And your JavaScript:
function changeFrame(link) {
$('#first iframe').attr("src", $(link).attr('href'));
$('#second iframe').attr("src", $(link).attr('secondary-href'));
return false;
}
Note that it'd be more idiomatic jQuery to do this without any onClick handlers, but simply initialise it all in your <head>/<script> from the beginning:
<script type="text/javascript">
$(function() {
$("a.iframe-link").click(function(event) {
$("#first iframe").attr("src", $(link).attr("href"));
$("#second iframe").attr("src", $(link).attr("secondary-href"));
// Whatever used to be the activebutton, make it 'waitingbutton', and remove
// the 'activebutton' class.
$(".activebutton").
addClass("waitingbutton").
removeClass("activebutton");
// Remove .waitingbutton from this, add .activebutton.
$(this).removeClass("waitingbutton").addClass("activebutton");
// Don't allow the link's default action (to follow the href in the normal
// way).
event.preventDefault();
});
});
</script>
Then later:
<a class="iframe-link waitingbutton" href="yes.html" second-href="whatever.html">Hello!</a>