Multiple Functions with one Code - javascript

so I'm using this code, to slideToggle a box on my webpage.
// OPEN CERTAIN BOX
$(function() {
var sliding = false;
var mq = window.matchMedia( "(min-width: 700px)" );
if (mq.matches) {
var time = 500;
} else {
var time = 0;
}
var id = ('1');
var div = ('#toggle-content-' + id);
var img = ('#toggle-img-' + id);
var toggler = ('toggler-' + id);
$(div).hide()
$(toggler).click(function() {
if (sliding == false) {
sliding = true;
// Open / Close
$( div ).slideToggle(time,"swing");
// ...
As you can see, I'm using the var id, to use the toggle function for a certain box, which has its own css and html code.
I have 7 more boxes. Until now, i copied the code 7 times and changed the id at each copy from 2 - 8. Is there a way to make it with one code?
I tried a for loop, that goes from 1 - 8 but this obviously didnt work.
Has someone an idea? Or do I have to make that 8 copies and changed the id.
Edit:
My approach with the for-loop:
$(function() {
var sliding = false;
var mq = window.matchMedia( "(min-width: 700px)" );
if (mq.matches) {
var time = 500;
} else {
var time = 0;
}
for(i = 1; i <= 8; i++){
var id = (i.toString());
var div = ('#toggle-content-'+id);
var img = ('#toggle-img-'+id);
var toggler = ('toggler-'+id);
$( div ).hide()
$( toggler ).click(function(){
if (sliding == false){
sliding = true;
// Open / Close
$( div ).slideToggle(time,"swing");
...
And this is my html code for one box:
<tr><td cellspacing="0" cellpadding="0" height="50px" class="upper">
<toggler-1><area-head-text><img id="toggle-img-1" src="images/box_opener.png"/>Starterpaket</area-head-text></toggler-1>
</td></tr>
<tr><td>
<div id="toggle-content-1">
<area-head-text>
<img class="text-image" src="images/arrow.png"/>3 individuelle Entwürfe<br>
<img class="text-image" src="images/arrow.png"/>3 Korrekturzeichnungen<br>
<img class="text-image" src="images/arrow.png"/>Internationale Nutzungsrechte<br>
<img class="text-image" src="images/arrow.png"/>400€<br><br>
</area-head-text>
</div>
</td></tr>

I'm not sure why you put "Obviously" a loop doesn't work, because that's pretty much exactly what you should do. Something like this:
for(var i = 1; i <= 8; i++)
{
var div = $('#toggle-content-' + i);
var img = $('#toggle-img-' + i);
var toggler = $('toggler-' + i);
$(div).hide()
$(toggler).click(function() {
if (sliding == false) {
sliding = true;
// Open / Close
$( div ).slideToggle(time,"swing");
// ...
}

This is 2 options.
(and my preference) -
Instead of using an ID to add the click event onto each individual toggle button, use the same class on each, and add the click event on that class. When the user clicks a toggle button traverse the DOM from the clicked toggle button to perform your toggle on the relevant <div>.
This would look something like:
$(function() {
$('.toggleBtn').click(function() {
var sliding = $(this).data('sliding'); //use data attr to store sliding status
if (sliding == false) {
$(this).data('sliding') = true;
}else {
return; //don't toggle we're sliding
}
// navigate to element and toggle
$(this).parent('.someParentElement').children('.theDiv').slideToggle(time,"swing");
//clear sliding status
$(this).data('sliding', false);
}
}
The reason this is my preference, is because although it's faster to target an ID for a click event than a class for a single event, using 7 click events on 7 different IDS in my opinion (I don't know for sure) is less efficient than using a single click event on 1 class. That's my perceived purpose of using events on classes rather than IDS.
Also this way, when you want to add another box in, or remove a box, you don't need to modify any Javascript, the only thing you would need to maintain this code for is if you decide to change the structure of the HTML, and therefore the navigation of the DOM to perform your toggle.
using your method:
var ids = ["id1","id2","id3"];
for(var id in ids) {
var $div = $('#toggle-content-' + id);
var $img = $('#toggle-img-' + id);
var $toggler = $('toggler-' + id);
$div.hide()
$toggler.click(function() {
if (sliding == false) {
sliding = true;
// Open / Close
$div.slideToggle(time,"swing");
// ...
}

Related

Is there a way to add an event listener on two separate divs and be able to know when the user clicked outside of one by itself?

I am writing Javascript code that shows pictures on a category based on the ones the user clicked on but will show all categories when clicked outside the filtered pictures. Yet, I need the same code to work on separate divs independently, not the whole dom.
Attaching the event listener to the document works except, as you may have guessed, it doesn't work on two divs independently. When I attach it to a reference dom, let's day the dom id, it works but it doesn't know when the user clicked outside
document.addEventListener("click", (evt) => {
//get an array of all the div with "column" class
var imgElements = imgGrid.getElementsByClassName("column");
var w, x;
var y, z;
let targetElement = evt.target; // clicked element
do {
//itirate through all the divs we got the reference for
for (var i = 0; i < imgElements.length; i++) {
//check if we click on any of those divs
if (targetElement.className == imgElements[i].className) {
//we clicked on a div
//let's get the class name we want to filter by
w = imgElements[i].className;
x = w.split(' ');
console.log("You clicked on a: " + x[1]);
//we're not done //let's go itirate those divs once more
//but this time for everyone that don't have a class that
//matched our filter class we hide it, else we show it
for (var i = 0; i < imgElements.length; i++) {
y = imgElements[i].className;
z = y.split(' ');
if (z[1] != x[1]) {
addClass(imgElements[i], "hidden");
} else {
removeClass(imgElements[i], "hidden");
}
}
return;
}
}
// Go up the DOM.
targetElement = targetElement.parentNode;
} while (targetElement);
console.log("You clicked outside");
//other useful things being done here
});
Instead of "document.addEventListener" I will say DomId.addEventlistner and expect it to know to when I clicked inside and outside of each dom reference.
You can give DIVs that should be 'clickable' an unique class name. That way your logic doesn't have to know each 'inside' DIVs id.
function handleClick(e) {
if (e.target.className != "clickableDiv") {
console.log("clicked outside");
} else {
var element = e.target.id;
console.log(element + " clicked");
}
}
document.addEventListener("click", handleClick);
<div id="container1" class="clickableDiv">
DIV1
</div>
<div id="container2" class="clickableDiv">
DIV2
</div>
<div id="container3">
I'm not clickable
</div>

tags underneath headings disappear when clicked again w/ javascript no idea why

I have pasted the javascript below but also a link to my codepen so you can see exactly what I am talking about.
I would like the heading to be clicked and expose the text below. On another click I would like for the text to go back to hidden. Multiple headings can be opened at the same time. What is happening with my current setup is you can click once to show, click again to hide and then when you click again to show nothing shows, if you keep clicking the text and headings below are eaten/dissapear. I would prefer to do this without jquery. thanks for any help.
http://codepen.io/jrutishauser/pen/YPrrNa
var clickToShow = function () {
if (this.nextElementSibling.className === 'open'){
this.nextElementSibling.remove('open');
} else if (this.nextElementSibling.className != 'open') {
this.nextElementSibling.className = 'open';
}
};
var articleHeadings = document.getElementsByTagName('h3');
for (var index = 0; index < articleHeadings.length; index++){
articleHeadings[index].onclick = clickToShow;
}
var subArticleHeadings = document.getElementsByTagName('h4');
for (var index2 = 0; index2 < subArticleHeadings.length; index2++){
subArticleHeadings[index2].onclick = clickToShow;
}
Change this.nextElementSibling.remove('open') to this.nextElementSibling.className = ''. I believe remove() method removes the element, not the class.
You can do it like this also. This is the correct way of doing it.
var clickToShow = function () {
element=this.nextElementSibling;
if (element.className === 'open'){
element.className=element.className.replace('open','');
} else if (element.className != 'open') {
element.className = 'open';
}
};

How to reduce 180 lines of code down to 20 in Javascript?

I have a lot of click handler functions which are almost (textually and functionally) identical. I've got a menu with maybe 10 items in it; when I click on an item, the click handler simply makes one div visible, and the other 9 div's hidden. Maintaining this is difficult, and I just know there's got to be a smart and/or incomprehensible way to reduce code bloat here. Any ideas how? jQuery is Ok. The code at the moment is:
// repeat this function 10 times, once for each menu item
$(function() {
$('#menuItem0').click(function(e) {
// set 9 divs hidden, 1 visble
setItem1DivVisible(false);
// ...repeat for 2 through 9, and then
setItem0DivVisible(true);
});
});
// repeat this function 10 times, once for each div
function setItem0DivVisible(on) {
var ele = document.getElementById("Item0Div");
ele.style.display = on? "block" : "none";
}
Create 10 div with a class for marking
<div id="id1" class="Testing">....</div>
<div id="id2" class="Testing">....</div>
<div id="id3" class="Testing">....</div>
and apply the code
$('.Testing').each(function() {
$(this).click(function() {
$('.Testing').css('display', 'none');
$(this).css('display', 'block');
}
}
$(document).ready(function (){
$("div").click(function(){
// I am using background-color here, because if I use display:none; I won't
// be able to show the effect; they will all disappear
$(this).css("background-color","red");
$(this).siblings().css("background-color", "none");
});
});
Use .siblings() and it makes everything easy. Use it for your menu items with appropriate IDs. This works without any for loops or extra classes/markup in your code. And will work even if you add more divs.
Demo
Fiddle - http://jsfiddle.net/9XSJW/1/
It's hard to know without an example of the html. Assuming that there is no way to traverse from the menuItem to ItemDiv - you could use .index and .eq to match up the elements based on the order they match with the selector.
var $menuItems = $("#menuItem0, #menuItem1, #menuItem2, ...");
var $divs = $("#Item0Div, #Item1Div, #Item2Div, ...");
$menuItems.click(function(){
var idx = $(this).index();
// hide all the divs
$divs.hide()
// show the one matching the index
.eq(idx).show();
})
Try
function addClick(i) {
$('#menuItem'+i).click(function(e) {
// set nine divs hidden, 1 visble
for( var j = 0; j < 10; ++j ) {
var ele = document.getElementById("Item"+j+"Div");
ele.style.display = (i == j ? "block" : "none");
}
});
}
// One click function for all menuItem/n/ elements
$('[id^="menuItem"]').on('click', function() {
var id = this.id; // Get the ID of the clicked element
$('[id^="Item"][id$="Div"]').hide(); // Hide all Item/n/Div elements
$('#Item' + id + 'Div').show(); // Show Item/n/Div related to clicked element
});
Obviously this would be much more logical if you were using classes instead:
<elem class="menuItem" data-rel="ItemDiv-1">...</elem>
...
<elem class="ItemDiv" id="ItemDiv-1">...</elem>
$('.menuItem').on('click', function() {
var rel = $(this).data('rel'); // Get related ItemDiv ID
$('.ItemDiv').hide(); // Hide all ItemDiv elements
$('#' + rel).show(); // Show ItemDiv related to clicked element
});
Save the relevant Id's in an array - ["Item0Div", "Item1Div", ...]
Create a generic setItemDivVisible method:
function setItemDivVisible(visible, id) {
var ele = document.getElementById(id);
ele.style.display = visible ? "block" : "none";
}
And set your click handler method to be:
function(e) {
var arrayLength = myStringArray.length;
for (var i = 0; i < idsArray.length; i++) {
setItemDivVisible(idsArray[i] === this.id, idsArray[i]);
}
}
I think this will do the trick

Fade effect on display="block" action in Javascript

I have some javascript that is switching between 3 divs on click of 1 of 3 tabs.
Here is my Javascript:
(function($){
$.fn.acidTabs = function(options) {
var settings = {
'style' : 'one'
};
options = $.extend( settings, options );
return this.each (function () {
var o = options;
container = this;
container.setAttribute("class",o.style);
var navitem = container.querySelector("li");
//store which tab we are on
var ident = navitem.id.split("_")[1];
navitem.parentNode.setAttribute("data-current",ident);
//set current tab with class of activetabheader
navitem.setAttribute("class","tabActiveHeader");
//hide two tab contents we don't need
var pages = container.querySelectorAll(".tabpage");
for (var i = 1; i < pages.length; i++) {
pages[i].style.display="none";
}
//this adds click event to tabs
var tabs = container.querySelectorAll("li");
for (var i = 0; i < tabs.length; i++) {
tabs[i].onclick=displayPage;
}
});
// on click of one of tabs
function displayPage() {
var current = this.parentNode.getAttribute("data-current");
//remove class of activetabheader and hide old contents
document.getElementById("tabHeader_" + current).removeAttribute("class");
document.getElementById("tabpage_" + current).style.display="none";
var ident = this.id.split("_")[1];
//add class of activetabheader to new active tab and show contents
this.setAttribute("class","tabActiveHeader");
document.getElementById("tabpage_" + ident).style.display="block";
this.parentNode.setAttribute("data-current",ident);
}
};
})(jQuery);
I cant seem to modifiy this to accept fading effects. Or maybe there is a better way to do this?
Would love your help!
Thank you.
it's not easy because you can't do it.
You need to split the two css statements.
New div with opacity:0 and display:none
change display to block
and then change opacity using setTimeout (even a 10ms delay will do).
do the opposite for the div that will hidden.
something like this:
var newdiv=document.getElementById("tabpage_" + ident);
newdiv.style.display="block";
setTimeout(function(){newdiv.style.opacity="1";},10);
OK figured it out with some help from the asp.net forum. Replace the function displayPage() with this:
var current = this.parentNode.getAttribute("data-current");
//remove class of activetabheader and hide old contents
$('#tabHeader_' + current).removeClass('tabActiveHeader');
$('#tabpage_' + current).hide();
var ident = this.id.split("_")[1];
//add class of activetabheader to new active tab and show contents
$(this).addClass("tabActiveHeader");
$('#tabpage_' + ident).fadeIn();
this.parentNode.setAttribute("data-current",ident);

Jquery: Blur function does not work with Div tag

I am trying to create a Jquery Tree plugin for my current project. In the plugin, there are 3 compomnents: a text box containing the result selected from the tree , a div containing the tree and a button to show the div. It works fine, except that i cannot make it auto lose the popup div if the tree lose its focus.
Here is the code to create the div
createTree = function() {
$.getJSON(_options.jsonSrc, function(data) {
nDiv = document.createElement("div");
nDiv.id = "divRootAd";
$(nDiv).css('display', 'none');
jsonObj = data["treeJson"];
nUl = document.createElement("ul");
nUl.appendChild(createNode(jsonObj));
nDiv.appendChild(nUl);
$("body").append(nDiv);
//$(nDiv).focus();
repositionDiv();
});
};
repositionDiv = function() {
if ($('#divRootAd').is(':hidden')) {
// get the field position
var sf_pos = $("#txtAdVal").offset();
var sf_top = sf_pos.top;
var sf_left = sf_pos.left;
// get the field size
var sf_height = $("#txtAdVal").height();
// apply the css styles - optimized for Firefox
$("#divRootAd").css("position","absolute");
$("#divRootAd").css("left", sf_left);
$("#divRootAd").css("top", sf_top + sf_height + 5);
$('#divRootAd').show();
$('#divRootAd').blur(function(event){
alert("lose focus");
clearDiv();
});
} else {
clearDiv();
}
};
The line alert("lose focus") does not work when i move the mouse outside the div. Can anyone suggest a solution for this ?
Instead of blur you could use mouseout
$('#divRootAd').mouseout(function(event){
alert("lose focus");
clearDiv();
});
Hope it helps

Categories

Resources