JS multiple function execution - javascript

I am using the youtube loadingbar tool found at www.onextrapixel.com, and it's pretty straightforward with regards to everything.
However, I have multiple <a> tags that have different href attributes and will load the content area (target) with different content. The problem is when I initialize the loadingbar function to a class, say:
$('ajax-call').loadingbar(options);
and I have multiple a tags with the same class say:
<a id ="link1" class = "ajax-call" href="hello1.html" data-type="POST" data-target="#Content_Area">Link 1</a>
<a id ="link2" class = "ajax-call" href="hello2.html" data-type="POST" data-target="#Content_Area">Link 2</a>
<a id ="link3" class = "ajax-call" href="hello3.html" data-type="POST" data-target="#Content_Area">Link 3</a>
<a id ="link4" class = "ajax-call" href="hello4.html" data-type="POST" data-target="#Content_Area">Link 4</a>
In this example I have 4 links, so the ajax call, along with success and done functions, is repeated 4 times. Each time it loads the same (correct) content and executes the same functions (correct functions) for each respective link, but it does that 4 times, which results in completely messed up everything, since I am initializing other objects (which get initialized 4 times).
All the content looks correct but nothing in the content area works (modals, etc.).
If I make only one link in the side menu, all works fine. If I initialize each link separately by ID, all works fine, but if I group them all in one class, this happens. How do I solve this?

classes starts with a period
$('.ajax-call').loadingbar(options);
And it looks like the plugin is poorly written, it does not return this.each(function().. it simply does
$.fn.loadingbar = function(options){
el = $(this),
href = el.attr("href"),
target = el.data("target"),
...etc
so calling it on a collection of elements probably doesn't work properly, try
$('.ajax-call').each(function() {
$(this).loadingbar(options);
});

Related

Issue with tree traversal, finding div ID to be used variably - jquery

so I've been trying to figure this out but I'm coming up short. Have really tried searching the best I could to come up with the answer, including jQuery API documentation and other SO posts. I feel like I'm almost there but I'm either misunderstanding something or I'm approaching this goal incorrectly.
For multiple different sections, I have 2 clickable icons in separate div's, 1 (lets say iconA) shown on load and 1 hidden (iconB) on load. When (iconA) is clicked, it hides the [sectionA] where (iconA) is located then shows the [sectionB] where (iconB) is located. I then want (iconB) to hide [sectionB] and show [sectionA].
Clearly I can't use toggle because one of the sections is always hidden at any given point. And since I'm trying to write a script that I can use for multiple sections and multiple icons, with different names, I can't just set 1-1 class names for ALL icons and sections.
I've created a jsfiddle to illustrate. Below I'll write a quick example.
HTML:
<div class="sectionAparent>
<div class="sectionA" id="example>
<i class="fa fa-code contbtn">iconA (shown on load)</i>
</div>
</div
<div class="sectionB" id="exampleSHOW">
<i class="fa fa-minus minushide">iconB (hidden on load)</i>
</div>
jQuery:
$('.contbtn').click(function(){
var contid = $(this).attr('id');
$('#'+contid+'show').slideToggle(1000);
$(this).hide(1000);
});
-this first one is to hide sectionA and show sectionB, which works fine.
$('.minushide').click(function(){
var cbtn = $(this).closest('.sectionB').siblings('.sectionAparent').find('div[id]');
var cid = $(cbtn).attr('id')
$('#'+cid+'show').slideUp(1000);
$(cid).slideDown(1000);
});
-So my thoughts were to jump up to the closest ancestor that is a sibling to the section containing the ID that I need. Then find the div with that ID, retrieve that ID, and use it show the section containing the ID and hiding the section with the ID+more. The goal is for this to be variable for multiple different sections with similar naming conventions without having to hard-code the section names in a list inside my script.
Hope this makes sense and I apologize for the wall of text, just wanted to make sure I conveyed what I'm trying to do and where I'm at. If my logic is incorrect or there is an easier way to do this, then I'm all ears! Thanks.
https://jsfiddle.net/dankbawls/wnjxwyfy/
You forgot to append the '#' character to sid in the second last line of the js
Updated fiddle
$('#'+sid).slideDown(2000);
Since you are using class (sectionhide) to toggle visibility, you can look into .toggleClass method.
It has an overriden constructor to accept 2 arguments, className and state (a boolean value)
Based on this state, it will add/remove class. True means add and false means remove
$('.minushide, .contbtn').on("click", function() {
var container = $(this).closest('.container');
var nextContainer = container.next('.container').length > 0 ? container.next('.container') : container.prev('.container');
container.toggleClass('sectionhide', true)
nextContainer.toggleClass('sectionhide', false)
})
Sample Fiddle
Note: I have added a common class container to both divs to have a common pattern
For a carousel kind of behaviour, you can use index to find index of element to be shown and hide all.
Sample Fiddle

Inserting class of clicked element and ID of parent into another image

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>

How to create a see-more/Read-more feature requiring only anchors in the html?

I'm working on a site which will be maintained by not so tech savvy people, and I need to be able to give them the ability to add "see-more" anchors which use Jquery slide up/down to reveal their content.
My code works well for a single instance of the read more, but when there are multiple instances of this, it gets fairly screwed up.
javascript/jquery
$(".see-more").nextUntil(".see-less").wrapAll("<div class='see-more-content'></div>");
$(".see-less").hide();
var count= 1
/*
$(".see-more-content").each(function(){
var count= count+1;
$(this).data("count",count);
console.log(count);
});
*/
$(".see-more-content").slideUp(0);
$(".see-more").click(function(){
$(".see-more-content").slideToggle();
$(".see-more").hide();
$(".see-less").show();
});
$(".see-less").click(function(){
$(".see-more-content").slideToggle();
$(".see-less").hide();
$(".see-more").show();
});
HTML
<a class="see-more">See More...</a>
<ul>
<li>Advanced Elastic search Technology </li>
<li>Document Text Search</li>
<li>Embed Code Web Publishing for Images, Video & PDFs</li>
<li>Video Management with HTML5 Full</li>
<li>Previews On the Fly Conversions and Transcoding</li>
<li>Print on Demand</li>
<li>Stylized Collections (Lightboxes/Galleries)</li>
<li>Alerts and Notifications</li>
<li>Comments, Ratings and Favorites</li>
<li>WordPress and Drupal CMS Integrations</li>
<li>Dropbox Integration</li>
<li>Asset Level Performance Analytics • Site Activity Analytics Dashboard</li>
<li>Unlimited Custom User Access Levels</li>
<li>Integrated Content Contribution and Workflow</li>
<li>Personal Profile Management</li>
<li>Mobile App and Site </li>
<li>Watermarking</li>
<li>Rights Management</li>
<li>All New Feature Releases3</li>
</ul>
<a class="see-less">See Less...</a></div>
What I want to happen:
I want everything between the anchor with class see-more and anchor with class see-less, to get wrapped in a div, which when the anchor for see-more is clicked that div jquery slides down, when see-more is clicked, and slides up when see-less is clicked.
What is happening:
It works perfect when there is only one instance of see-more and see-less in a page. https://jsfiddle.net/TheWebTech/by3LsLuu/
When there are multiple instances of see-more and see-less in the html, the contents of all see-more+see-less blocks after the first instance are all moved/wrapped into the first block instances of the see-more see-less blocks get added.
https://jsfiddle.net/TheWebTech/by3LsLuu/4/
How do I prevent everything from being wrapped into the first instance of the see-more see-less block and instead have each one get wrapped separately?
Bonus but not really required: how can I make each see-more section slide up/down separately from eachother?
If you're going to keep the layout the same, you can use .prev() and .next() jQuery methods to determine which selector group you're referring too. Here's an updated fiddle with two instances:
https://jsfiddle.net/szva79d6/1/
First, I've made it so that your wrapping function applies to each selector individually, like so:
$(".see-more").each(function() {
$(this).nextUntil(".see-less")
.wrapAll("<div class='see-more-content'></div>");
});
What I've done in the two event methods is to make each event only act on the previous or next siblings, so that your events are properly delegated to each dynamically wrapped element.
$(".see-more").click(function() {
var $more = $(this),
$content = $more.next(".see-more-content"),
$less = $content.next(".see-less");
$content.slideToggle();
$more.hide();
$less.show();
});
$(".see-less").click(function() {
var $less = $(this),
$content = $less.prev(".see-more-content"),
$more = $content.prev(".see-more");
$content.slideToggle();
$less.hide();
$more.show();
});
You need to target specific to itself, try this:
$(".see-more").click(function(){
$(this).next(".see-more-content").slideToggle(); // find next content and show
$(this).hide(); // hide the see more button
$(this).nextAll('.see-less').first().show(); // show the next see less button
});
$(".see-less").click(function(){
$(this).prev(".see-more-content").slideToggle();
$(this).hide();
$(this).prevAll(".see-more").first().show();
});
Here's an updated fiddle

A function with changing variable, dependent on a class

So, first some background.
I have 9 types of rooms that are displayed as thumbnails with the name. What I want to do is that on click "Additional Information" - the rooms with disappear and the expanded version of a chosen room type will appear with the description and bigger picture. Also, there is an ability to go next and previous in the expanded view. I do not have a problem with this expansion and previous/next. BUT!
Here is what I am trying to achieve: if the code looks approximately like
<ul id="room_holder">
<li><div class="room 1">Additional Info</div></li>
<li><div class="room 2">Additional Info</div></li>
and so on...
And the expandable area will look something like:
<div id="expandable">
<div id="picture">Blah-blah-blah, some description, etc</div>
</div>
So, basically, what I can't figure out is how to get the needed slide to show when the correspondint thumbnail is pressed. I know I can do the .addClass method, and copy the code 9 times, for each of the numbers (1-9). But I believe it is 9 times more compact if I have some sort of function, that gets the second class name (the number) by using .split(' ')[1] and then using it as part of the variable in the part which opens the corresponding expandable view. So, my question is: how do I do this? I am a newbie with javascript, but try to learn on the go!
Oh, and the codepen that I've been trying to deal with is:
http://codepen.io/godban/pen/QbZmxz
Firstly, you should use data-* attribute instead of classes (new in HTML5) data attributes, w3school :
<ul id="room_holder">
<li><div class="room" data-room="1">Additional Info</div></li>
<li><div class="room" data-room="2">Additional Info</div></li>
Then, use the click function from jQuery .click( handler ), use it this way to know which one has been clicked :
$(".room").click(function(event){
var target = event.currentTarget;
var room = $(target).data("room");
alert(room);
});

Navigation Works Once, But Then Does Nothing

I'm trying to code a navigation bar with four elements. If the element is currently selected it will have a "red" background image, if it is one of the other 3, it will have a "black" background image. my four tabs are 'timetable, homework, notifications and sport'
I tried making 8 functions like the 2 below
function setTimeRed()
{
document.getElementById("time").style.ClassName = 'timetable_r';
}
function setTimeBlack()
{
document.getElementById("time").style.ClassName = 'time_r';
}
And then four blocks like this:
function changeTimeButton()
{
var timePath = new String();
timePath = document.getElementById("timetable").style.backgroundImage;
if(timePath == "url(assets/img/tabs/time_black.png)" || timePath == "")
{
setTimeRed();
setHomeBlack();
setNotiBlack();
setSportBlack();
}
else {
}
}
finally, my html has this:
<div id="tabbar">
<ul id="tabs">
<a href"#" onclick="changeTimeButton()">
<li id="timetable" class="time_b">
<p>Timetable</p>
</li>
</a>
<a href"#" onclick="changeHomeButton()">
<li id="homework" class="home_b">
<p>Homework</p>
</li>
</a>
<a href"#" onclick="changeNotiButton()">
<li id="notifications" class="noti_b">
<p>Notifications</p>
</li>
</a>
<a href"#" onclick="changeSportButton()">
<li id="sport" class="sport_b">
<p>Sport</p>
</li>
</a>
</ul>
</div>
It works once then does nothing. Why?
I think error is in your script, just one example
document.getElementById("time").style.ClassName = 'timetable_r';
which should be (there are no elements with id "time" in your html, at least in the code you posted here)
document.getElementById("timetable").style.ClassName = 'timetable_r';
Another thing, if it works once, then seems it might save some issues with new session or existing session. I am not an expert on javascript. But if it helps, please inform.
When turning the background color off, you need to remove any existing classes like this:
document.getElementById("timetable").className =
document.getElementById("timetable").className.replace
( /(?:^|\s)time_b(?!\S)/ , '' )
Since you're using classes instead of modifying the styles in the javascript, you should stick to that. You seem to be trying to set the background image in the javascript.
Instead, you should apply that background image to the class' styles in the CSS.
Using a framework like jQuery would make this much easier since it has helper functions such as addClass(), toggleClass(), and removeClass(). You should also set the 'a' tags inside the 'li'. It makes for cleaner code in my opinion. The browser will still read the click and be able to apply the classes correctly.
Also, you shouldn't have to repeat yourself so often in your code. One solution is to create a generic function and pass the element's id in as a parameter. Then, you use an 'active' class instead of 'timetable_r'. The active class will be applied to the active link and you won't have to write the functions out so many times. Hope this helps.

Categories

Resources