Changing Snippet syntax to use this keyword - javascript

i am just building a small snippet to hide a div checkout my snippet :
var Modal = function(){
Modal.prototype.hide = function(elem){
return elem.hide();
// i basically want to change the above line to this.hide();
}
}
$(document).ready(function(){
var _str = new Modal();
var div = $('#mydiv');
_str['hide'](div);
});
now , the reason i built this snippet is because i wanted to understand the code in modal.js and how it works , lets checkout the code in modal.js .
checkout this line :
data[option](_relatedTarget)
data is basically an instance of Modal
[option] is basically Modal.prototype.toggle(param)
and (_relatedTarget) is basically the parameter being passed .
so basically whats happening on that line is , the following function is being called .
hide(_relatedtarget).
I console.logged _relatedtarget and found out , it is basically an HTML element , looks something like below :
<a data-target="#myModal" data-toggle="modal" class="btn btn-primary btn-lg">
if you have a look at the toggle function , it looks something like below :
Modal.prototype.toggle = function (_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
so bascially we are passing the following parameter in the above function :
<a data-target="#myModal" data-toggle="modal" class="btn btn-primary btn-lg">
and it all works fine .
Now , lets review th hide function in my code :
Modal.prototype.hide = function(elem){
return elem.hide();
}
see how my hide function differs in the sense that, i am using the following syntax to hide my code :
elem.hide();
whereas the code in modal.js uses the following syntax :
this.hide()
but if i use the above syntax and run my code , the code does't work and the element is not hidden.
so my question is, how can i change the syntax in my code to :
this.hide() and make my code work, Fiddle of my example is here .
Thank you .
Alexander.

For this function to work without a parameter, the div needs to be known by the Modal. You could do it by passing the container's selector to your constructor, like so:
var _str = new Modal('#modal-container');
And assigning it as a property of Modal. Example code:
var Modal = function(containerSelector) {
this.container = $(containerSelector);
Modal.prototype.hide = function() {
return this.container.hide();
}
}
// Using a setTimeout for the demo, so you can see it first
setTimeout(function() {
var _str = new Modal('#modal-container');
_str['hide']();
},1000);
#modal-container {
height: 100px;
width: 100px;
background: #aaa;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This div will hide after 1 second:</p>
<div id="modal-container"></div>
Edit: don't confuse jQuery's hide() function (called on DOM elements) with your own (called on a Modal object). Check this fiddle, it implements a toggle() function just like you have at line 48.

Related

Variable value not accumulating?

Hey I'm very new to JS but cannot figure out why the 3 variables at the top aren't accumulating?
var xe = 0;
var reckon = 0;
var books = 0;
document.getElementById('#go').addEventListener('click', function(){
questionOne();
});
document.getElementById('#macos').addEventListener('click',function(){
addXe();
questionThree();
});
document.getElementById('#windows').addEventListener('click',function(){
questionThree();
});
document.getElementById('#linux').addEventListener('click', function(){
questionThree();
});
document.getElementById('#large').addEventListener('click', function(){
questionFour();
addXe();
});
function addXe(){
xe++;
};
function addReckon(){
reckon++;
};
function addBooks(){
books++;
};
The rest of the code is simply a series of functions that toggles divs display on and off.
If Ive missed and important info out let me know,
Thanks!
EDIT:
github.com/daffron/accountingsoftware
I thought it would be easier to attach the whole site, the problem is each time the addXero function is executed , it doesn't accumulate the value of var xero, I have it printing to console in the other functions. Thanks –
Your parameters for document.getElementById() are wrong.
If your HTML code for a button is like this:
<input type="button" id="go" />
<!-- OR like this: -->
<button id="go" ></button>
Then your javascript code must access the button using the method getElementById() as:
document.getElementById("go");
So, one of your functions will be like:
document.getElementById('go').addEventListener('click', function(){
questionOne();
});
BUT, if you've used '#go' because you were referring to a CSS Selector then you've to use querySelector method instead of getElementByIdas:
document.querySelector("#go");
So, a function call as per your code will be:
document.querySelector('#go').addEventListener('click', function(){
questionOne();
});
you should have html label example
<label id="xeLbl">test</label>
and after changing value you should apply it to html label.
function addXe(){
xe++;
document.getElementById('xeLbl').innerHTML = xe;
};

Specify name of button via JQuery

I've have code to add button via JQuery, It is used to remove row. Button working correctly, just It's without name like [], but should be like [X]. It looks like HTML code created as: <button class="removeRow"></button> instead of <button class="removeRow">X</button>
JQuery
$.fn.optionTest.defaults = {
removeLinkOptions: {
class: 'removeRow',
href: 'javascript:;'
}
};
var removeRow = $.fn.optionTest.createColumn($("<button>", options.removeLinkOptions));
removeRow = $($(removeRow).html());
row.append(label).append(CertNo).append(PlaceofIssue).append(from).append(to).append(removeRow);
Where should I apped this X to achieve It?
If something unclear - just ask, if needed I can create JS fiddle.
Should be in this line ,when creating button:
var removeRow = $.fn.optionTest.createColumn($("<button>", options.removeLinkOptions).text("X"));

How to change class name of two IDs at same time using js?

I have two IDs in same name ! if any one clicked among them , i need to change the class name of the both IDs. i know we should use ID for single use. Because of my situation(I have two classes for button ) so i have moved to ID.
Her is my code if i click one id that name only changes another one is remains same
<button class="success" id="1" onClick="reply(this.id)"> Added </button>
<button class="success" id="1" onClick="reply(this.id)"> Added </button>
js function
function reply(clicked_id)
{
document.getElementById(clicked_id).setAttribute('class', 'failed');
var el = document.getElementById(clicked_id);
if (el.firstChild.data == "Added")
{
el.firstChild.data = "Add";
}
}
if i use instead of 'class' to id while renaming class which one will be renamed success class or 'class name 1' ?
You can't. Getelementbyid will only return one element. Probably the first one.
Pure JS Is Second Example
My JS Fiddle Example: http://jsfiddle.net/eunzs7rz/
This example will use the class attribute only to perform the switching that you need, its a extremely basic example as do not want to go beyond what is needed... Also i forgot to remove the id's in the JS Fiddle Example.. so just ignore them
THE CSS:
.success {
background-color:#00f;
}
.failed {
background-color:#f00;
}
THE HTML:
<button class="success"> Added </button>
<button class="success"> Added </button>
THE JAVSCRIPT:
$(function() {
$(".success").click(function(){
Reply(this);
});
});
function Reply(oElm) {
$(oElm).attr('class', 'failed');
}
EDIT - PURE JAVASCRIPT VERSION
Sorry, did not think to check the post tags if this was pure JS. But here you go anyway ;)
<style>
.success {
background-color:#00f;
}
.failed {
background-color:#f00;
}
</style>
<button class="success" onclick="Reply(this)"> Added </button>
<button class="success" onclick="Reply(this)"> Added </button>
<script>
function Reply(oElm) {
oElm.className = 'failed';
}
</script>
THE MAIN THING HERE
Once you have the element either by using 'this' or by using 'getElementBy', you can then simply use ".className" to adjust the class attribute of the selected element.
As already explained by others, id is for single use and is quicker than using class or type. So even if you have a group, if only one is ever used.. use an id.
Then you use the object/reference of 'this' from an event on an element, in this case the onclick... that will send that variable to the function / code called.
So using 'this' is a preferred option as it will always reference the element that it is used/called from.
pass elemenet, not it's Id
<button class="success" id="1" onClick="reply(this)"> Added </button>
<button class="success" id="1" onClick="reply(this)"> Added </button>
function reply(elem)
{
$(elem).setAttribute('class', 'failed');
if (elem.firstChild.data == "Added")
{
elem.firstChild.data = "Add";
}
}
the ID attribute must be unique or else it will get the last defined element with that ID.
See this for reference.
Use a class instead of an id. ids are supposed to be unique in a dom tree.
html:
<button class="success" onClick="reply()"> Added </button>
<button class="success" onClick="reply()"> Added </button>
js:
var ary_success = document.querySelectorAll(".success"); // once and forever. If the set of elements changes, move into function `reply`
function reply () {
var elem;
var s_myclasses;
for (var i=0; i < ary_success.length; i++) {
elem = ary_success[i];
s_myclasses = elem.getAttribute('class');
s_myclasses = s_myclasses.replace ( /(success|failed)/g, '' );
s_myclasses = s_myclasses + ' failed';
elem.setAttribute('class', s_myclasses );
if ( elem.firstChild.data.indexOf("Added") !== -1) {
elem.firstChild.data = "Add";
}
}
}
Live Demo here.
Notes
Make sure that you set ary_successin the onload handler or in an appropriately placed script section - at the timeof execution the buttons must be present in the dom ! If in doubt, move it to the start of reply' body.
If you employ jquery, the code simplifies (well...) to:
$(document).ready( function () {
$(".success").on ( 'click', function ( eve ) {
$(".success").removeClass("success").addClass("failed");
$(".success *:first-child:contains('Added')").text(" Add ");
});
});
Updates
Notes, Live Demo
Iterator method changed, every not supported on test platform

How to find div that has matching data attr then remove class

Here is my attempt that doesn't seem to be working:
$('container').find("[data-slider='" + one + "']").removeClass('hidden');
Here is the full function that is wrapped in a document. ready function
$("#service-icon").on('click', function(){
var $this = $(this);
event.preventDefault();
$this.addClass('ease-transition').toggleClass('active-slider-btn');
$(".page-wrapper").find("[data-slider='" + one + "']").toggleClass("hidden");
});
The error that I am getting is:
"Uncaught ReferenceError: one is not defined"
Things to check:
Is `container` a class or id? If so you'll need to add a `.` or `#` respectively
That the expression in the `.find()` function returns what you're expecting
Can you post a link to a JSFiddle or something?
I have a working example here that is similar to your situation.
HTML
<div class="container">
<div data-slider="1" class="hidden">1</div>
<div data-slider="2">2</div>
</div>
<button id="show-1">show slider 1</button>
CSS
.hidden {
display: none;
}
JavaScript
var one = "1";
$("#show-1").click(function(e){
$(".container").find("[data-slider='" + one + "']").removeClass("hidden");
});
Something like this has to work:
$('.page-wrapper').find("[data-slider='" + one + "']").removeClass('hidden');
See it working here: http://jsfiddle.net/sNp7x/2/
Maybe the data attribute is set via javascript as well, so you have to be aware of the timing?!

Does className exist in Mootools?

I want to update this very simple JS to Mootools 1.2 and it's not easy.
This function :
function changeclass(x){
document.getElementById("content").className = "ziclass0";
document.getElementById("content").className = "ziclass" + x;
}
is triggered in the DOM by :
<div id="someclass">
a href="javascript: changeclass(0)">Unstyled</a
a href="javascript: changeclass(1)">link one</a
a href="javascript: changeclass(2)">link two</a
a href="javascript: changeclass(3)">link three</a
</div>
to call the according CSS classes like :
.ziclass1 h1{
color: rgb(142,11,0);
font-family: Verdana;
font-size: 2.5em;
letter-spacing: 0.1em;
}
and changes the layout accordingly in :
<div id="content" class="ziclass3"> ... </div>
I know I can add an event to the triggers like :
$(#someclass.each(function(element,index) {
element.addEvent('click', function(){
//some code
});
But, how do I get #content class classname ?
Through an array ?
I am a bit confused here.
I'd be really grateful for any help to set me on the right track
These are very basics of MooTools. Anyway, here's how you change a class name of a collection of elements:
$$('#container a').each(function(link){
link.addEvents({
click: function(e){
e.stop();
this.set('class', 'newClassName');
// to append a class
// this.addClass('appendThisClass');
}
});
});
Here's a working example: http://jsfiddle.net/oskar/9fxxr/
It's all in the documentation: http://mootools.net/docs/core/Element/Element
But this is not exactly what i was asking.
The triggering element (a) calls a css element by looping through its number located in "href".
EX :
a href="javascript: changeclass(1)">Link One</a
// calls all CSS classes named .ziclass1 and applies/adds them in "content"
a href="javascript: changeclass(2)">Link Two</a
// calls all CSS classes named .ziclass2 and applies/adds them in "content"
USING
function changeclass(x){
document.getElementById("content").className = "ziclass" + x;
}
RESULT :
HTML:
a href="javascript: changeclass(1)">Link One</a
a href="javascript: changeclass(2)">Link Two</a
<div id="content" class="ziclass1">
...
</div>
That's why I was thinking about an array.
Around this idea :
var myArray = ["0","1","2", etc ...];
function myFunction() {
myArray.each(function(value, index, array){
$(value).addEvent('click',function(event) {
console.log(value);
// add my class here
});
});
};
myFunction();
where I'd get the value of the array located in the href like this :
a href="1">Link one</a
a href="2">Link two</a
and change the class accordingly.
But I dont know how to do this.

Categories

Resources