How to set marginLeft property using JavaScript? - javascript

I used the following code to set the left margin for a div with id=""
document.getElementById('s4-ca').style.marginLeft = '0px';
However getting an error like Object Required!
UPDATE - My code
<script type="text/javascript">
var groupName;
$().SPServices({
operation: "GetGroupCollectionFromUser",
userLoginName: $().SPServices.SPGetCurrentUser(),
async: false,
completefunc: function(xData, Status) {
$(xData.responseXML).find("[nodeName=Group]").each(function()
{
groupName = $(this).attr("Name");
});
}
});
if($.trim(groupName) != 'ABC')
{
document.getElementById('s4-leftpanel').style.display = 'none';
document.getElementById('s4-ca').style.marginLeft = '0px';
}
</Script>

There's nothing wrong with your JavaScript, just give the <div> a matching id property, then it should work fine, i.e.
<div id="s4-ca"></div>
So there reason you're getting the error is because document.getElementById('s4-ca') doesn't find a en element with a matching id, so it's null, and you can't reference the style property on a null object.
Also, when you set the marginLeft there's no need to specify units for zero, you can use just 0.
document.getElementById('s4-ca').style.marginLeft = "0";

Not reproducible: http://jsfiddle.net/VH2z2/
I assume you call document.getElementById before the element is available.
Either include the code on the bottom of the page or in the load event handler, e.g.
window.onload = function() {
document.getElementById('s4-ca').style.marginLeft = '0px';
};
You should not do this if there is other JavaScript code which might set a load event handler (you would overwrite it).

Something like this possibly?
$('#s4-ca').css({ marginLeft: 0 });

the problem is "object requierd"
that means that
document.getElementById('s4-ca')
returns nothing, you must make sure an element with id 's4-ca' exists

$('#s4-ca').css({ marginLeft: 0 });
or
$('#s4-ca').css('margin-left', 0 );
your code is not jquery, but the code above is the way to do this in jquery, both work.
update: your error message probably means that there is no element with id="s4-ca", please check for such an element! see this jsfiddle: http://jsfiddle.net/4DzyW/ where your code just works.

if you want to use jQuery (according to your question's tag)
$("#s4-ca").css('marginLeft','0px');
.css Api of jQuery

Related

Slider Pro Slide Count

Using slider-pro, I am having trouble getting slide count for the number of slides inside the carousel. I have looked at this solution, but am having no luck. My code looks like this:
$(document).ready(function($) {
$('.slider-pro').sliderPro();
});
var slider = $( this ).data( 'sliderPro' );
$(this).append('<div class="counter"><span class="active">'+ (parseInt(slider.getSelectedSlide()) + 1) +'</span>/'+slider.getTotalSlides()+'</div>');
slider.on( 'gotoSlide', function( event ) {
$(this).find('.counter .active').text(event.index + 1);
});
But I get a console error:
TypeError: slider is undefined, can't access property "getSelectedSlide" of it
I am not much of a jquery guy, so I'm not sure why it is giving me this error when in fact the property getSelectedSlide is defined in the jquery.sliderPro.js file. Perhaps I'm not calling it correctly or need to bind the property to a class or id. I'm not sure. I've tried both, but nothing seems to work.
Thanks so much!
Unfortunately, I'm using the class selector to initialize multiple sliders on the same page with the same parameters. I don't want to use id because I will have to create a unique id for every slider instance, which I don't want and will become unmanageable. I also cannot dynamically generate an id for each slider. An example page is here:
BFMagazine
Right now, I have to hardcode the slider number/total into every slide, which isn't ideal.
The relevant Slider-Pro js used is:
$(document).ready(function($) {
$('.slider-pro').sliderPro({
width: '100%',
arrows: true,
fadeArrows: false,
buttons: false,
fade: true,
fadeDuration: 200,
thumbnailPosition: 'bottom',
thumbnailWidth: 75,
thumbnailHeight: 75,
autoplay: false,
fullScreen: false,
breakpoints: {
480: {
thumbnailWidth: 40,
thumbnailHeight: 40
}
}
});
$.each('.slider-pro', function() {
var slider = $('.slider-pro').data('sliderPro');
$('.slider-pro').append('<div class="counter"><span class="active">' + (parseInt(slider.getSelectedSlide()) + 1) +
'</span>/' + slider.getTotalSlides() + '</div>');
slider.on('gotoSlide', function(event) {
$('.slider-pro').find('.counter .active').text(event.index + 1);
});
});
});
I'm getting a console error:
TypeError: cannot use 'in' operator to search for 'length' in '.slider-pro'
I am using jquery-2.1.4.min.js
Any suggestions would be greatly appreciated.
Thanks so much!
It's a simple issue actually the code you have found is missing some other details regarding how it's being used; that code need to be used inside an object or event handler context so this will refer to the object but in your case you are trying to use it outside so there is no context for this therefore we can't use it as such.
Anyway as you have told you are new to jquery that's fine; what you need to do is instead of using this use the css selector directly if you are "outside", so you have
var slider = $('.slider-pro').data( 'sliderPro' );
// here this is not ok as it is "outside"
$('.slider-pro').append('<div class="counter"><span class="active">'+ (parseInt(slider.getSelectedSlide()) + 1)
+'</span>/'+slider.getTotalSlides()+'</div>');
slider.on('gotoSlide', function( event ) {
$(this).find('.counter .active').text(event.index + 1);
// here this is ok as it is "inside"
});
Update:
You were almost there but instead of using this each you were needed to use this each, the difference between the two is that the second one specially used for Dom nodes and you can use this magic inside to refer to each item without actually giving them any explicit property like ids
$('.slider-pro').each(function(index, element) {
//using $(element) instead of $(this) should work too
$(this).sliderPro({
//..options
});
var slider = $(this).data('sliderPro');
$(this).append('<div class="counter"><span class="active">' + (parseInt(slider.getSelectedSlide()) + 1) +
'</span>/' + slider.getTotalSlides() + '</div>');
slider.on('gotoSlide', function(event) {
$(this).find('.counter .active').text(event.index + 1);
// finds only the .counter and .active inside the current slider divsnot touching .counter and .active of other slider divs
});
});
A brief explanation would be, the $(selector).each(..) loops over all the Dom nodes that match the selector and gives you a context this that will always refer to the current item of the iteration but only within the scope of each function.For instance if matched items are a set of <div>s then you can refer to each <div> individually

Detect position and hide a element

I'm trying to hide a button while a div have style positioned as 0.
The whole JS code to explain is:
$('#left-button').click(function() {
event.preventDefault();
$('#myTab').animate({
left: "+=200px"
}, "fast");
});
The code above WORKS. If I click on the button (left-button), the "mytab" div goes to the left. Now, I want to hide the #left-button, when the #myTab has style "left:0".
I tried this:
if ($('#myTab').css('left') == '0') {
$('#left-button').style.display = "none";
}
The basic style is
#myTab { width:300px; height:300px; position:relative; left:0; background:#777 }
#left-button {width:200px; height:200px; background:#ccc; }
There's no debug errors but nothing happens. What can I do?
If there's another method instead Js, let me know too.
Thank you very much.
http://jsfiddle.net/SgMDa/
You were just missing the unit value px
if ($('#myTab').css('left') == '0px') {
$('#left-button').hide();
}
And use .hide() instead style.display = "none";
Working Fiddle
The main problem in your code is with the line $('#left-button').style.display = "none"; and you have missed 'px' in the if condition if ($('#myTab').css('left') == '0') {
The if should be if ($('#myTab').css('left') == '0px') {
$ object returns jQuery wrapped array / object, what you are trying to access is the actual DOM element, so you have two options to access DOM element:
1. Using jQuery method hide()
$('#left-button').hide();
or
2. Using DOM property display
$('#left-button')[0].style.display = "none";
NOTE:
The jQuery Object: The Wrapped Set: Selectors return a jQuery object
known as the "wrapped set," which is an array-like structure that
contains all the selected DOM elements. You can iterate over the
wrapped set like an array or access individual elements via the
indexer ($(sel)[0] for example). More importantly, you can also apply
jQuery functions against all the selected elements.
Official information about jQuery Object
I think it is like you are getting value from left, try using the offset function
if ($('#myTab').offset().left == 0) {
$('#left-button').hide();
}
.css gives you measurement in px so you should try :
if ($('#myTab').css('left') == '0px') {
$('#left-button').style.display = "none";
}

Looping through generated HTML with jQuery

I know if I wanted to bind events to generated HTML, I'd need to use something like .on(), but I've only used it when binding events like .click().
I'm creating a web app that applys a list of colors. Colors are generated from a JSON file. Once fetched, I add it to the page, with certain information contained in attributes. I'd like to do something with the new generated HTML, which is list-elements. But what console.log() is showing me is there is nothing in the parent ul. Even though on the page I see the newly added content.
Here's the entire code based around it.
var setColors = function(){
getColors = function(){
$.getJSON('js/colors.json', function(colors) {
$.each(colors, function(i, colors) {
//console.log(colors);
$('<li>', {
text: colors['color'],
'name' : colors['color'],
'data-hex' : colors['hex'],
'data-var' : colors['var']
}).appendTo('#picker');
})
});
addColors();
}
addColors = function(){
var el = $('#picker').children;
$(el).each(function(){
console.log($(this));
});
}
return getColors();
}
$(function(){
setColors();
});
addColors() is where I'm having trouble with. The error says 'Uncaught TypeError: Cannot read property 'firstChild' of null. How can I work with the newly generated HTML?
You are missing parentheses on the children method:
var el = $('#picker').children();
Also, if you want the addColor method to be executed on the newly generated html, then you must add a call to it after the html is generated, from within the getJSON callback method.
addColors = function(){
var el = $('#picker').children;
$(el).each(function(){
console.log($(this));
});
}
A few issues:
missing end semi-color
missing parentheses on .children()
children() returns a jQuery object, no need for $(el)
Updated:
window.addColors = function(){
var $el = $('#picker').children();
$el.each(function(){
// do stuff here, but could attach each() to above, after children()
});
};

JQuery, a new Selection using the results

Is there a way to me do this?
<img id="example" src="anything.jpg" title="something" class="abc" />
$('.abc').each(function(){
//test if this result is something
if( $(this)...(???)...('[src^=anything]')) == 'anything.jpg'){
}
//another Jquery selector test for this one
if( $(this)...(???)...('#example').size() > 0){
}
});
This is just an example, what I need is pretty more complex.. But I would like to know if there is a way to make other jQuery selector test in the result of a first selector.. since "find" will find the children of $(this).. and .parent() get alot of brothers..
See what I mean?
Do you have any idea?
So sorry.. let me try again..
$('div').each();
get all "div", right?
But now in that function I need to make another "test" check if div class is "red" or "blue"..
See?
I need to test something else of the result based in Jquery selector..
I know I could do:
class = $(this).attr('class'); and then if(class=="blue"){} .. But I would like to do $('this[class=blue]').size()>0){}
The jQuery is() filter operates on a found set to detect if something is true or not.
The jQuery filter() method will further pare down a found set based on criteria.
var allDivs = $('div');
var greenOnes = allDivs.filter('.green');
var redOnes = allDivs.filter('.red' );
I think you need the is method:
$('.abc').each(function() {
$(this).is('[src^=anything]')
});
This is fairly simple though, but I can't really tell what you are trying to do by the description. Maybe this is enough to get you started though.
You can use the filter and is methods to filter/search within a jQuery object.
if( $(this).is('[src^="anything"]') ) {
}
elseif( $("#example").size() > 0) {
}
You could put $("#example") in a variable outside of the loop and then reference it inside the loop as well.
if(this.src.indexOf("anything") === 0) {
// source starts with 'anything'
}
if($("#example").length) {
// since there can be only one #example
// in a *valid* document
}
Based on your edit:
if($(this).hasClass("blue")) {
...
}
?

Replacing fields with jQuery

Why is line 10 returning null?
http://pastie.org/720484
it works with line 40
You do not seem to have a proper grasp of the siblings() operator. You also were not utilizing jQuery's val() function and were missing periods on some of your class names. To locate the address1 class you would need to do the following:
var $checkbox = jQuery(this);
$checkbox.parent().siblings('.formField').find('.address1');
Also, you would want the alert to be
alert($checkbox.parent().siblings('.formField').find('.address1').val());
to alert the value of the input box.
FIXED AND OPTIMIZED VERSION:
function update_address(eventObject) {
var $checkbox = jQuery(this);
var $siblings = $checkbox.parent().siblings('.formField');
if ($checkbox.attr('checked')) {
$siblings.find('.address1').val($('.hidden_address1').val());
$siblings.find('.address2').val($('.hidden_address2').val());
$siblings.find('.city').val($('.hidden_city').val());
$siblings.find('.state').val($('.hidden_state').val());
$siblings.find('.zip').val($('.hidden_zip').val());
$siblings.find('.province').val($('.hidden_province').val());
$siblings.find('.country').val($('.hidden_country').val());
} else {
$siblings.find('.address1').val('');
$siblings.find('.address2').val('');
$siblings.find('.city').val('');
$siblings.find('.state').val('');
$siblings.find('.zip').val('');
$siblings.find('.province').val('');
$siblings.find('.country').val('');
}
}
try fetching the input:text's .val() instead
On line 9, shouldn't it be var checkbox = $(this); instead? I've not seen the jQuery() function used like that.
Because <input class="address1"/> is not a sibling of <input id="parent_sameAsBefore"/>. I think you want:
checkbox.parent().parent().find('.address1');
Why not just go with finding the form fields using absolute path?
Unless your DOM is very convoluted (and you need relative paths), I would prefer this approach myself.
Also use .val() to get and set values.
function update_address(eventObject) {
if($(this).attr('checked')) {
$('#parent_address1').val($('hidden_address1').val());
$('#parent_address2').val($('hidden_address2').val());
$('#parent_city').val($('hidden_city').val());
$('#parent_state').val($('hidden_state').val());
$('#parent_zip').val($('hidden_zip').val());
$('#parent_province').val($('hidden_province').val());
$('#parent_country').val($('hidden_country').val());
}
else {
$('#parent_address1').val("");
$('#parent_address2').val("");
$('#parent_city').val("");
$('#parent_state').val("");
$('#parent_zip').val("");
$('#parent_province').val("");
$('#parent_country').val("");
}
}
Note, seems to be a bug in the original code in line 15:
checkbox.siblings('.tate').value = $('hidden_state').value;
Should be:
checkbox.siblings('.state').value = $('hidden_state').value;
alert(checkbox.siblings('.address1').html() ); // This should be
alert(checkbox.parent().siblings('.address1').html() );
//Checkbox does not have siblings
Line 10

Categories