I am trying to convert the JavaScript to jQuery for my carousel.
The code I had is:
document.querySelectorAll('.indicators')[0].style.color = 'red';
document.querySelector('.toggler-prev').style.display = 'none';
document.addEventListener('postchange', function(event){
document.querySelectorAll('.indicators')[event.lastActiveIndex].style.color = 'white';
document.querySelectorAll('.indicators')[event.activeIndex].style.color = 'red';
var togglerPrev = document.querySelector('.toggler-prev');
var togglerNext = document.querySelector('.toggler-next');
if (event.activeIndex === 3) {
togglerPrev.style.display = 'block';
togglerNext.style.display = 'none';
} else if (event.activeIndex === 0) {
togglerNext.style.display = 'block';
togglerPrev.style.display = 'none';
} else {
togglerNext.style.display = 'block';
togglerPrev.style.display = 'block';
}
});
Which I transferred to jQuery:
$('.indicators').css('color','#000');
$('.toggler-prev').css('display','none');
$(window).on('postchange', function(event){
$('.indicators')[event.lastActiveIndex].css('color','#FFF');
$('.indicators')[event.activeIndex].css('color','#000');
var togglerPrev = $('.toggler-prev');
var togglerNext = $('.toggler-next');
if (event.activeIndex === 3) {
togglerPrev.css('display','block');
togglerNext.css('display','none');
} else if (event.activeIndex === 0) {
togglerNext.css('display','block');
togglerPrev.css('display','none');
} else {
togglerNext.css('display','block');
togglerPrev.css('display','block');
}
});
But it isn't working as I expected for example togglers are not being hidden and color of indicators not being changed.
This is the working JS example: http://codepen.io/anon/pen/eJYWQO
And my jQuery alternative: http://codepen.io/anon/pen/eJYWrq
Can anybody help me with editing my second codepen? Thanks in advance.
You forgot to mention somewhere that you are using AngularJS and onsenUI ;)
Your problem is, that the jQuery event does not have the properties activeIndex and lastActiveIndex, but they can be found in event.originalEvent.
Also, like #stalin said in his answer, your indicators are no jQuery objects, therefore you can't call the css-function on them. Wrap this stuff in another jQuery constructor like $() or even better, use the eq-function which returns a jQuery wrapped object from an array.
Then, to optimize some of the readability, you might want to consider the hide and show function instead of changing the CSS property display.
All in all your code should look like this
$('.indicators').css('color', '#fff');
$('.indicators').eq(0).css('color', '#000'); // highlight the first indicator
$('.toggler-prev').hide();
$(window).on('postchange', function(event) {
//store the indices for readability
var activeIndex = event.originalEvent.activeIndex;
var lastActiveIndex = event.originalEvent.lastActiveIndex;
$('.indicators').eq(lastActiveIndex).css('color', '#FFF');
$('.indicators').eq(activeIndex).css('color', '#000');
var togglerPrev = $('.toggler-prev');
var togglerNext = $('.toggler-next');
if (activeIndex === carousel.getCarouselItemCount() - 1) {
togglerPrev.show();
togglerNext.hide();
} else if (activeIndex === 0) {
togglerNext.show();
togglerPrev.hide();
} else {
togglerNext.show();
togglerPrev.show();
}
});
You have several problems in your implementation
First the event is not trigered in $(window) is in the $(document)
Your variable like lastActiveIndex are not in the event object are in event.originalEvent
$('.indicators')[event.lastActiveIndex] return a dom object not a jquery object you need to wrap this result in a jquery object to use the css() function
After you fix all this your code will work
Sorry that don't have time for create a fiddle for you :)
Related
Hi I'm getting script error for below code. as I tried all the ways but no luck .
kindly help me as I'm very new to this field. atleast tell me where am I going wrong
<body onload="hightlightMoreLink(2210);hightlightMoreLink(2211);">
function hightlightMoreLink(groupID) {
var isHightlightRequired = top.document.Main.isOtherLabelingCountriesPresent(groupID) var moreLinkColumnElement = "";
var moreLinkElement = "";
if (groupID == 2210) {
moreLinkColumnElement = document.getElementById("MoreLinkTH");
moreLinkElement = document.getElementById("labelingMoreLink");
} else {
moreLinkColumnElement = document.getElementById("MoreLinkTHUnblind");
moreLinkElement = document.getElementById("labelingMoreLinkUnblind");
}
if (isHightlightRequired) {
moreLinkColumnElement.style.backgroundColor = "#26339f";
moreLinkElement.style.color = "#fff";
} else {
moreLinkColumnElement.style.backgroundColor = "#f5f5f5";
(getting error on this line)
moreLinkElement.style.color = "#26339f";
}
}
Here it is working...
function hightlightMoreLink(groupID) {
var isHightlightRequired = 1
var moreLinkColumnElement="";
var moreLinkElement="";
if (groupID==2210) {
moreLinkColumnElement = document.getElementById("MoreLinkTH");
moreLinkElement = document.getElementById("labelingMoreLink");
} else {
moreLinkColumnElement = document.getElementById("MoreLinkTHUnblind");
moreLinkElement = document.getElementById("labelingMoreLinkUnblind");
}
if (isHightlightRequired) {
moreLinkColumnElement.style.backgroundColor = "#26339f";
moreLinkElement.style.color="#fff";
} else {
moreLinkColumnElement.style.backgroundColor = "#f5f5f5";
moreLinkElement.style.color="#26339f";
}
}
hightlightMoreLink(2210)
First of all, you should create a fiddle so people can better understand the problem.
Checking your code though, I think the problem is in this line:
var isHightlightRequired = top.document.Main.isOtherLabelingCountriesPresent(groupID)
Check if it is return a boolean.
Aside from that, I think you should work with classes to manipulate the elements' styles. The onload you're putting on the body is not a good practice either. Jquery has a function for that purpose.
$( document ).ready(){
hightlightMoreLink(2210);
}
Another thing I would point out is the fact that you could use jquery to manipulate the elements. As is:
$("#MoreLinkTH").css("background-color", "#26339f");
$("#labelingMoreLink").css("color", "#fff");
I'm trying to check if an element is display block, and if it is then i want to execute some code. Below is my code, its a large function but where I'm trying to check if a div is display block is at the bottom, and if it is display block then i want to execute the blur method.
As you can see near the bottom, I started writing if ($suggestionsWrapper === and my intention was to write if suggestions wrapper is display none, then do this. I just can't figure out how to execute this, what I've written doesn't work. Also I am new to all of this so sorry if this is really messy or doesn't make sense, still very much learning.
//Header Search Handler
function headerSearchHandler(){
var $searchInput = $(".header-search input[type=text]"),
$searchSubmit = $(".header-search input[type=submit]"),
$mobSearchBtn = $(".mobile-search-btn"),
$myAccountText = $(".menu-utility-user .account-text"),
$miniCart = $("#header #mini-cart"),
$searchForm = $(".header-search form"),
$headerPromo = $(".header-promo-area");
$suggestionsWrapper = $('#suggestions-wrapper');
//
$mobSearchBtn.on("click touchend", function(e) {
$(this).hide();
//$myAccountText.hide();
$searchInput.show();
$searchInput.addClass('grey-line');
$searchSubmit.show();
$miniCart.addClass("search-open");
$searchForm.addClass("search-open");
setTimeout(function() {
$searchInput.addClass("active").focus();
}, 100);
e.stopPropogation();
});
$searchInput.on("click touchend", function(e) {
$searchInput.addClass('grey-line');
e.stopPropogation();
}).blur(function(e) {
var $this = $(this);
if($this.hasClass("active")){
$this.removeClass("active");
$searchSubmit.hide();
$mobSearchBtn.show();
$miniCart.removeClass("search-open");
$searchForm.removeClass("search-open");
}
});
$searchInput.focus(function(e){
$(this).css('width', '145px');
})
if ($suggestionsWrapper.css('display') == 'none') {
$searchInput.blur(function(e){
$(this).removeClass('grey-line');
$(this).css('width', '145px');
}
})
}//End Header Search Handler
You can create a helper method to check if display is block or not :
function checkDisplay(element) {
return $(element).css('display') == 'block';
}
Then you can check it like :
if(checkDisplay("#myElement")){
console.log("Display is Block")
}
else {
console.log("Display is NOT Block")
}
here is an example : https://jsfiddle.net/fafgqv7v/
You can do something like this I think:
if ($suggestionsWrapper.css('display') == 'block')
{
// true
} else {
// false
}
Based off of your code I think you have the }) wrong, it should be:
if ($suggestionsWrapper.css('display') == 'none') {
$searchInput.blur(function(e){
$(this).removeClass('grey-line');
$(this).css('width', '145px');
})
}
I hope this helps!
Thanks in advance for any help I can get with this one. I'm working on a project which requires me to create buttons out of select options. The buttons are being created without issue, but I can't figure out for the life of me why the onclick trigger isn't firing. I've recoded this in jQuery too and am having the same issue. I'll post both.
JS (with a bit of JS):
var buttonObj = {
addButtons: function() {
$('select').each( function() {
// Check that buttons don't already exist
var selectBox = $(this);
if(!selectBox.parent().next().hasClass('button-group')) {
// Create button div
var buttonGroup = document.createElement('div');
buttonGroup.className = 'button-group';
// Check which type of button to create
var buttonLen = selectBox.children().length;
if(buttonLen > 3) {
// Long button classes
var buttonClass = 'decision-button long';
} else {
// Short button classes
var buttonClass = 'decision-button';
}
selectBox.parent().parent().append(buttonGroup);
// Create Buttons
for(var i = 1; i < buttonLen; i++) {
var newButton = document.createElement('button');
newButton.className = buttonClass;
newButton.type = "button";
newButton.innerHTML = selectBox.children().eq(i).html();
buttonGroup.appendChild(newButton);
newButton.onclick = function() {
alert($(this));
$(this).siblings().removeClass('selected');
$(this).addClass('selected');
}
}
} else {
console.log('do nothing');
}
});
}
}
buttonObj.addButtons();
The Answer
I wasn't checking for $(document).ready() because I was lead to believe that if you're loading the JS at the bottom of the DOM, it is unnecessary. In this case, it was totally necessary.
Thanks to all those who helped.
I think jQuery got an easy way to bind dynamically elements.
jQuery provides .on() (or .live() for older version) for this.
Example:
jQuery(document).ready(function(){
var btnClass=".someClass";
$(document).on('click',btnClass,function(e){
alert($(this));
$(this).siblings().removeClass('selected');
$(this).addClass('selected');
});
});
I can not find out what is going wrong while running.
Here I'm trying to re-write JavaScript to jQuery syntax.
What exactly is incorrect? What I'm doing wrong.
Legacy >>
var cssmenuids = ["navmenu"];
function createcssmenu()
{
for (var i = 0; i < cssmenuids.length; i++)
var ultags = document.getElementById(cssmenuids[i]).getElementsByTagName("ul");
for (var t = 0; t < ultags.length; t++)
{
ultags[t].style.top = ultags[t].parentNode.offsetHeight + "-1px";
ultags[t].parentNode.onmouseover = function()
{
this.style.zIndex = 100;
this.getElementsByTagName("ul")[0].style.visibility = "visible";
this.getElementsByTagName("ul")[0].style.zIndex = 0;
}
ultags[t].parentNode.onmouseout = function()
{
this.style.zIndex = 0;
this.getElementsByTagName("ul")[0].style.visibility = "hidden";
this.getElementsByTagName("ul")[0].style.zIndex = 100;
}
}
}
}
if (window.addEventListener)
window.addEventListener("load", createcssmenu, false);
else if (window.attachEvent)
window.attachEvent("onload", createcssmenu);
jQuery Syntax >>
$(document).ready(function ()
{
$('ul#navmenu').height = $('ul#navmenu').parent.height + "-1px";
$('ul#navmenu').parent.bind('mouseover', function ()
{
$(this).css('z-index', 100);
$(this).$('ul')[0].css("visibility", "visible");
$(this).$('ul')[0].css('z-index', 0);
});
$('ul#navmenu').parent.bind('mouseout', function ()
{
$(this).css('z-index', 0);
$(this).$('ul')[0].css("visibility", "hidden");
$(this).$('ul')[0].css('z-index', 100);
});
});
That's it on JSfiddle http://jsfiddle.net/sublay/HCajr/
Related question JavaScript to jQuery syntax Building custom CSS horizontal menu
You're missing parenthesis on most of your calls.
Declaring the height should look like this
$('ul#navmenu').height($('ul#navmenu').parent().height() -1)
You need to use .parent() not .parent
$('ul#navmenu').parent().bind('mouseover'
Below, it seem as if you are trying to first the first available ul within #navmenu. When you use [0] you're actually calling .get() which converts the jQuery object to a javascript DOM element. Doing that will remove the ability for you to run jQuery functions against it. Also, chaining doesn't happen like that for selectors. Also, .css() will accept an object with key:value pairs.
$(this).find('ul:first').css({
"visibility" : "visible",
"z-index" : 0
});
Once again, missing the () for .parent()
$('ul#navmenu').parent().bind('mouseout',
And again, the selector chain is wrong.
$(this).find('ul:first').css({
"visibility" : "hidden",
'z-index' : 100
});
Height is a method, not a property. You have to set it likewise:
$('ul#navmenu').height($('ul#navmenu').parent.height + "-1px");
I'm having difficulty getting my textarea to expand vertically automatically.
I have some code to help make textarea auto expand vertically and for some reason it works when I clean out all my JS and provide a selector with reference to textarea e.g. $('textarea').autoGrow();
Calling the plugin on a chain of methods stops it from working. E.G.
micropostBox.hide().removeClass("micropost_content")
.addClass("micropost_content_expanded").show().autoGrow();
I established the plugin code works so copied all my working code to the same page and applied the autoGrow code to my textarea but it seems to be unresponsive. I noticed that the plugin I'm using the code from uses bind and unbind methods. In my code I use on and off methods from JQuery and wondering if this could be why the auto resizing of my textarea is not working?
Here is the code:
http://jsfiddle.net/erU5J/101/
autogrow plugin js code
$(function($) {
$.fn.autoGrow = function() {
return this.each(function() {
var txtArea = $(this);
var colsDefault = txtArea.attr('cols');
var rowsDefault = txtArea.attr('rows');
var updateSize = function() {
var linesCount = 0;
var lines = txtArea.attr('value').split('\n');
for (var i = lines.length - 1; i >= 0; --i) {
linesCount += Math.floor((lines[i].length / colsDefault) + 1);
}
if (linesCount >= rowsDefault) {
txtArea.attr('rows', linesCount + 1);
}
else {
txtArea.attr('rows', rowsDefault);
}
};
txtArea.unbind('.autoGrow').bind('keyup.autoGrow', updateSize).bind('keydown.autoGrow', updateSize).bind('change.autoGrow', updateSize);
});
};
});
my js code
$(function() {
$("div.microposts").on("focus", "textarea#micropostBox", function() {
var micropostForm = $(this).parent(),
micropostBox = micropostForm.find('textarea#micropostBox'),
micropostButton = micropostForm.find("input#micropostButton"),
xButton = micropostForm.find("div.xButton");
micropostBox.prop('rows', 7);
micropostForm.find('div#micropostOptions').removeClass('micropostExtraOptions');
micropostForm.find('div#postOptions').show();
$.trim(micropostBox.val()) == '' ? micropostButton.addClass("disabledMicropostButton").show()
:
micropostButton.prop('disabled', false);
micropostBox.hide().removeClass("micropost_content").addClass("micropost_content_expanded").show().autoGrow();
xButton.show();
micropostButton.prop('disabled', true);
micropostBox.off().on("keypress input change", function() {
micropostButton.prop({
disabled: !$.trim($(this).val()) != ''
});
$.trim($(this).val()) != '' ? micropostButton.removeClass("disabledMicropostButton").addClass("activeMicropostButton")
:
micropostButton.removeClass("activeMicropostButton").addClass("disabledMicropostButton");
});
xButton.on('click', function() {
micropostBox.removeClass("micropost_content_expanded").addClass("micropost_content");
micropostForm.find('div#micropostOptions').addClass('micropostExtraOptions');
micropostBox.val("");
micropostForm.find('div#postOptions').hide();
xButton.hide();
micropostButton.hide();
micropostBox.removeAttr('style');
micropostBox.prop('rows', 0);
micropostForm.find('.imagePreview > img').remove();
micropostForm.find('.imagePreview').hide();
});
});
});
$(function() {
$('div.microposts').on('click', 'li#addImage', function() {
var form = $(this).parents('form#new_micropost'),
fileField = form.find('input#micropost_image');
fileField.trigger('click');
});
});
$(function() {
$('input#micropost_image').change(function(evt) { //.off() make sautoresize work
var image = evt.target.files[0],
form = $(this).parents('form#new_micropost'),
imagePreviewBox = form.find('div.imagePreview'),
reader = new FileReader();
reader.onload = function(evt) {
var resultdata = evt.target.result,
img = new Image();
img.src = evt.target.result;
imagePreviewBox.show().prepend(img);
};
reader.readAsDataURL(image);
});
});
textarea
<textarea class="micropost_content" cols="40" id="micropostBox" name="micropost[content]" placeholder="" rows="0"></textarea>
It would be best to view a working example on jsfiddle. My aim is to have the auto resizing of textarea working before and after an image is added to the page using the image upload button in the textarea.
Kind regards
It depends if the method preceding the plugin call returned the jQuery object containing the elements to where the plugins need to be attached.
Here are a few examples of methods that do and do not return the elements you started with:
$('element') //get an element
.contents() //get an elements contents
.wrapAll('<div>') //wrapAll contents with div and returns the contents, not wrapper
.parent() //the wrapper
.parent() //the element
.myPlugin() //we attach a plugin to element
$('<div>')
.appendTo('body') //appendTo returns the same element, the div
.myPlugin() //attaches to the div
$('element') //get an element
.text() //get its text
.myPlugin() //chaining isn't possible since text() returns a string
Better read the docs for every method in jQuery and what it returns. Some DOM methods usually return the same element, some don't, and some don't return elements but values.
In summary, can plugins be attached after chains? YES, and it depends.
Refer to the jQuery's documentation
http://docs.jquery.com/Plugins/Authoring#Maintaining_Chainability