Is there a way to convert this jquery code to javascript? - javascript

I'm trying to create a tab menu. And I need this coded in regular javascript, not jquery.
$(document).ready(function() {
//When page loads...
$(".general_info_content").hide(); //Hide all content
$("ul.general_info_tabs li:first").addClass("active").show(); //Activate first tab
$(".general_info_content:first").show(); //Show first tab content
//On Click Event
$("ul.general_info_tabs li").click(function() {
$("ul.general_info_tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".general_info_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
return false;
});
});

The core of what you want to do is below - I'm sure there are a thousand different ways to do each task:
Remove a CSS class from an element:
var classes = document.getElementById([id]).className.split(" ");
for(var i = 0; i < classes.length; i++)
if(classes[i] == removeClass)
classes[i] = "";
document.getElementById([id]).className = classes.join(" ");
Add a CSS class to an element:
document.getElementById([i]).className += " " + addClassName;
Hide an element:
document.getElementById([i]).style.display = "none";
Fade an element:
// not tested, but based on tested/used code
function fade(el, opacity, fadeInTime) {
if (opacity < 100) {
el.style.opacity = opacity / 100;
el.style.filter = "alpha(opacity=" + opacity + ")";
opacity += 5;
setTimeout(function () { fade(el, opacity, fadeInTime); }, fadeInTime / 5);
}
}
To find all elements by CSS and tag name:
var matches = new Array();
var all = document.getElementByTagName(searchTagName);
for(var i = 0; i < all.length; i++){
if(all[i].className.replace(searchClassName, "") != all[i].className) {
matches.push(all[i].className);
}
}
// do something with (i.e., return or process) matches
And for the record, I find it encouraging, not unreasonable, that a person using the jQuery library wants to know how to do get things done with native JS/DOM.

More functions to complement Brian's post. Good luck.
EDIT: As I mentioned I would change the class=general_info_content to id=general_info_content1.
function attach(el, event, fnc) {
//attach event to the element
if (el.addEventListener) {
el.addEventListener(event, fnc, false);
}
else if (document.attachEvent) {
el["on" + event] = fnc; // Don not use attachEvent as it breaks 'this'
}
}
function ready() {
// put all your code within $(function(){}); here.
}
function init() {
attach(document, "readystatechange", function () {
if (document.readyState == "complete") {
ready();
}
});
}

Related

Multiple accordions simultaneously open. How to open only 1 JQuery accordion at a time

Currently open accordion is not closing when another opens.
This is the code I used, not sure where I got it wrong.
<script>
$(document).ready(function () {
//each accordion has a text entry and a corresponding image
var accordionEntries = document.querySelectorAll('.accordion-entry');
var accordionImages = document.querySelectorAll('.accordion-image');
for ( var i = 0; i < accordionEntries.length; i++ ) {
accordionEntries[i].dataset.target = 'accordion-image-' + i;
accordionImages[i].classList.add('accordion-image-' + i);
}
//toggles accordion open state
$(document).on('click', '.accordion-header', function () {
if ($(this).is(".accordion-open")) return $(this).removeClass("accordion-open");
var parent = $(this).closest('.accordion-entry, .accordion-image');
if(!parent.hasClass('.accordion-open')){
parent.toggleClass('accordion-open');
} else {
$('.accordion-open').removeClass('accordion-open')
}
$('.' + parent.data('target')).toggleClass('accordion-open')
})
})
</script>
Thanks for everyone's help in trying to answer the question, a colleague eventually helped me solve this. Here is the solution with comments for anyone else's benefit.
<script>
$(document).ready(function () {
var accordionEntries = document.querySelectorAll('.accordion-entry');
var accordionImages = document.querySelectorAll('.accordion-image');
for ( var i = 0; i < accordionEntries.length; i++ ) {
accordionEntries[i].dataset.target = 'accordion-image-' + i;
accordionImages[i].classList.add('accordion-image-' + i);
}
$(document).on('click', '.accordion-header', function () {
// close currently opened accordion
// add class to open clicked accordion
var accordionEntry = $(this).closest('.accordion-entry');
var open = 'accordion-open';
/* If the accordion that was clicked is in open state,
* remove all occurrences of the 'accordion-open' class and DO NOTHING
* AFTER.
*/
if (accordionEntry.hasClass('accordion-open')) {
accordionEntry.removeClass(open);
$('.' + open).removeClass(open);
} else {
/* If the accordion that was clicked is NOT in open state,
* remove all occurrences of the 'accordion-open' class and add 'accordion-open' class
*. to the accordion that was clicked.
*/
accordionEntry.removeClass(open);
$('.'+ open).removeClass(open);
accordionEntry.addClass('accordion-open');
$('.'+ accordionEntry.data['target']).addClass(open)
$('.'+ accordionEntry[0].dataset.target).addClass(open)
}
});
});
</script>

How to access links within repeat control via CSJS in XPages?

In my application I display a link in a repeat control. This link will open a dialog control which displays details for a chosen row in the repeat.
Now I want to make the links appear as "read" when they are clicked.
I have defined the following function that will register the link ID clicked in a cookie and change the CSS color property of the link.
I can store the link ID in a cookie but when I try to find it in the DOM and change the CSS I fail. What am I doing wrong?
// onclick
function saveId(id) {
if ($.cookie('idCookie')) {
$.cookie('idCookie', $.cookie('idCookie') + "," + id);
} else {
$.cookie('idCookie', id);
}
}
// make all links colored
function setVisited() {
if (null != $.cookie('idCookie')) {
var idArray = $.cookie('idCookie').split(',');
console.log("#ids:" + idArray.length);
for (var x = 0; x < idArray.length; x++) {
console.log("ID: " + x + "=" + idArray[x]);
if ($('#' + idArray[x]).length) {
//link exists
$('#' + idArray[x]).css('color', 'red');
}
}
}
// assign saveId()
$(document).ready(function() {
$('a').click(function() {
saveId($(this).attr('id'));
});
setVisited();
});
The problem is that you cannot use the : in your selector as described here:
How to get the element id in repeat control
so your code must look something like this:
// onclick
function saveId(id) {
if ($.cookie('idCookie')) {
$.cookie('idCookie', $.cookie('idCookie') + "," + id);
} else {
$.cookie('idCookie', id);
}
}
// make all links colored
function setVisited() {
if (null != $.cookie('idCookie')) {
var idArray = $.cookie('idCookie').split(',');
for (var x = 0; x < idArray.length; x++) {
var link = $(document.getElementById(idArray[x])).get();
if (link.length) {
$(link).css('color', 'red');
}
}
}
}
// assign saveId()
$(document).ready(function() {
$('a').click(function() {
saveId($(this).attr('id'));
});
setVisited();
});
good luck!
You probably need to use the x$ jQuery selector as your ids contains colons: https://openntf.org/XSnippets.nsf/snippet.xsp?id=x-jquery-selector-for-xpages.

jQuery Cookies: Remember Sate of Bootstrap Panel Heading

I would like to use jQuery Cookies to retain the state of my Bootstrap accordion. So far, this code is working well, but it only retains the state of the .panel .panel-collapse element.
jQuery(document).ready(function () {
//when a group is shown, save it as the active accordion group
jQuery("#checkout-accordion").on('shown.bs.collapse', function () {
var active = jQuery("#checkout-accordion .in").attr('id');
jQuery.cookie('activeAccordionGroup2', active);
// alert(active);
});
jQuery("#checkout-accordion").on('hidden.bs.collapse', function () {
jQuery.removeCookie('activeAccordionGroup2');
});
var last = jQuery.cookie('activeAccordionGroup2');
if (last != null) {
//remove default collapse settings
jQuery("#checkout-accordion .panel-collapse").removeClass('in');
//show the account_last visible group
jQuery("#" + last).addClass("in");
}
});
I would need another piece of code that sets the cookie for the .panel-heading element. It should remember class collapsed when the accordion panel is collapsed, and remove class collapsed when it's toggled/active.
There's also this code, which works well too, but only for the .panel .panel-collapse element, and not for .panel-heading also.
jQuery(document).ready(function() {
var lastState = localStorage.getItem('lastState');
if (!lastState) {
lastState = [];
localStorage.setItem('lastState', JSON.stringify(lastState));
} else {
lastStateArray = JSON.parse(lastState);
var arrayLength = lastStateArray.length;
for (var i = 0; i < arrayLength; i++) {
var panel = '#'+lastStateArray[i];
$(panel).addClass('in');
}
}
jQuery('#checkout-accordion').on('shown.bs.collapse', '.panel-collapse', function() {
lastState = JSON.parse(localStorage.getItem('lastState'));
if ($.inArray($(this).attr('id'), lastState) == -1) {
lastState.push($(this).attr('id'));
};
localStorage.setItem('lastState', JSON.stringify(lastState));
});
jQuery('#checkout-accordion').on('hidden.bs.collapse', '.panel-collapse', function() {
lastState = JSON.parse(localStorage.getItem('lastState'));
lastState.splice( $.inArray($(this).attr('id'), lastState), 1 );
localStorage.setItem('lastState', JSON.stringify(lastState));
});
});
Any ideas?

glitchy jquery div carousel

so i've made a jquery carousel which you can see here: http://teste.boleiafacil.com/ (it's the one in the end of the page
this is the jquery:
//highlights slide animation
var prdlength = $(".rproducts").length;
var prdleft = 1;
var i = 0;
function swapC() {
i++;
prdleft++;
$(".rproducts").each(function(){
$(this).animate({"left":"-" + prdleft + "px"}, 10);
if (prdleft == 180){
$(this).appendTo(".rproductswrapper");
prdleft = 0;
}
});
if (i == prdlength) {
i = 0
}
window.setTimeout(function() { swapC() }, 10);
}
$(window).on("load", swapC);
the problem is when the divs get appended to the end of the wrapper it looks glitchy.
how can i fix this?
Try wrapping your function in a document ready rather than window load, the shorthand for it is:
$(function(){
//code here
});

Click an anchor in a UIWebView with a UIButton

I have a Javascript function on my webpage that I'm displaying in a UIWebView:
$(document).ready(function() {
// index to reference the next/prev display
var i = 0;
// get the total number of display sections
// where the ID starts with "display_"
var len = $('div[id^="hl"]').length;
// for next, increment the index, or reset to 0, and concatenate
// it to "display_" and set it as the hash
$('#next').click(function() {
++i;
window.location.hash = "hl" + i;
return false;
});
// for prev, if the index is 0, set it to the total length, then decrement
// it, concatenate it to "display_" and set it as the hash
$('#prev').click(function() {
if (i > 1)
--i;
window.location.hash = "hl" + i;
return false;
});
});
So what I need to do is simulate an anchor click when my UIButton is clicked:
- (IBAction)next:(id)sender {
[animalDesciption stringByEvaluatingJavaScriptFromString:#"document.getElementById(\"next\").click();"];
}
But this doesn't work!
It works great on an HTML page, just by clicking the anchor that has an id of "next".
Any ideas why this won't work when clicking the button?
BTW I am able to call a standard javascript function like myFunc() with my current setup, but it won't do anything like this!
Any thoughts would be very appreciated!
You could implement javascript functions for next and previous and call that directly from your UIButton.
var i = 0;
function next() {
++i;
window.location.hash = "hl" + i;
return false;
}
function prev() {
if (i > 1)
--i;
window.location.hash = "hl" + i;
return false;
}
$(document).ready(function() {
// get the total number of display sections
// where the ID starts with "display_"
var len = $('div[id^="hl"]').length;
$('#next').click(function() {
next();
});
$('#prev').click(function() {
prev():
});
});
The call from your UIButton would be:
- (IBAction)next:(id)sender {
[animalDesciption stringByEvaluatingJavaScriptFromString:#"next()"];
}
By the way: I think you forgot to use len in the next() function to avoid stepping over the last display section.

Categories

Resources