Convert Jq to js - javascript

i can't add Jquery library to my codes and i have to use js code
can somebody help me with converting following code to js
thanks ..
<script type="text/javascript">
$(function(){
$("#gorightslide").click(function(){
if(!$(this).is('.diactiveisbtn')){
$(this).addClass('diactiveisbtn');
$("#goleftslide").removeClass('diactiveisbtn');
$("#oneblockshowblog").css({display:'none'});
$("#twoblockshowblog").fadeIn(500);
}
});
$("#goleftslide").click(function(){
if(!$(this).is('.diactiveisbtn')){
$(this).addClass('diactiveisbtn');
$("#gorightslide").removeClass('diactiveisbtn');
$("#twoblockshowblog").css({display:'none'});
$("#oneblockshowblog").fadeIn(500);
}
});
});
</script>

You can try this :
$(function(){
document.getElementById("gorightslide").click(function(){
if(!hasClass(this, 'diactiveisbtn')){
this.className += " diactiveisbtn";
document.getElementById("goleftslide").className = document.getElementById("goleftslide").className.replace(/\diactiveisbtn\b/,'');
document.getElementById("oneblockshowblog").style.display = "none";
fadeIn(document.getElementById("twoblockshowblog"));
}
});
document.getElementById("goleftslide").click(function(){
if(!hasClass(this, 'diactiveisbtn')){
this.className += " diactiveisbtn";
document.getElementById("gorightslide").className = document.getElementById("gorightslide").className.replace(/\diactiveisbtn\b/,'');
document.getElementById("twoblockshowblog").style.display = "none";
fadeIn(document.getElementById("oneblockshowblog"));
}
});
});
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
function fadeIn(el) {
el.style.opacity = 0;
var last = +new Date();
var tick = function() {
el.style.opacity = +el.style.opacity + (new Date() - last) / 400;
last = +new Date();
if (+el.style.opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
}
};
tick();
}

Try this
function yourfunction() {
document.getElementById("gorightslide").onclick = function(event) {
if(event.target.className != "diactiveisbtn"){
event.target.classList = "diactiveisbtn";
document.getElementById("goleftslide").classList = "";
document.getElementById("oneblockshowblog").style.display = "none";
document.getElementById("twoblockshowblog").style.display = "block"; // you can add here css animation (#keyframe)
}
}
document.getElementById("goleftslide").onclick = function(event) {
if(event.target.className != "diactiveisbtn"){
event.target.classList = "diactiveisbtn";
document.getElementById("gorightslide").classList = "";
document.getElementById("twoblockshowblog").style.display = "none";
document.getElementById("oneblockshowblog").style.display = "block"; // you can add here css animation (#keyframe)
}
}
}

You have a misunderstanding here, Jquery is made it with javascript, so, Your code is already in javascript. If you want to use this code in one function, you only need to remove the first line, it will looks like this:
<script type="text/javascript">
function callingPlugin(){
$("#gorightslide").click(function(){
if(!$(this).is('.diactiveisbtn')){
$(this).addClass('diactiveisbtn');
$("#goleftslide").removeClass('diactiveisbtn');
$("#oneblockshowblog").css({display:'none'});
$("#twoblockshowblog").fadeIn(500);
}
});
$("#goleftslide").click(function(){
if(!$(this).is('.diactiveisbtn')){
$(this).addClass('diactiveisbtn');
$("#gorightslide").removeClass('diactiveisbtn');
$("#twoblockshowblog").css({display:'none'});
$("#oneblockshowblog").fadeIn(500);
}
});
};
callingPlugin(); // <-- Will execute the code
</script>

Related

How to do this in jQuery?

I want to transform this code from JavaScript into jQuery.
This is the current code:
var i = 0;
var start = true;
document.getElementById("startclick").addEventListener("click", function() {
if (start) {
start = false;
interval = setInterval(function() {
i++;
document.getElementById('list').innerHTML += "albastru_" + i + '<br>' ;
}, 3000);
} else {
start = true;
clearInterval(interval);
}
});
Here is my attempt:
$x = 0;
$start = true;
$(document).ready(function () {
$('#buton2').on('click',function () {
if($start){
$start = false;
$interval = setInterval(function () {
$x ++;
$('#list').html('<p>albastru_</p>' + $x + '<br>'); }, 1000);
} else {
$start = true;
clearInterval($interval);
}
})
});
You can do something like below. I'm assuming startclick is a button, after you click it .append() will add the required data to #list div after 3 seconds.
Updated Answer with start and stop buttons.
var i = 0;
var start = true;
var interval = null;
$('#startclick').click(function() {
if (interval !== null) return;
interval = setInterval(function() {
i++;
$('#list').append("albastru_" + i + '<br>');
}, 3000);
});
$("#stop").click(function() {
clearInterval(interval);
interval = null;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="list">
</div>
<br />
<button id="startclick">START!</button>
<button id="stop">STOP!</button>

Updating interval dynamically - jQuery or Javascript

I have two "stopwatches" in my code (and I may be adding more). This is the code I currently use below - and it works fine. But I'd really like to put the bulk of that code into a function so I'm not repeating the same code over and over.
When I tried doing it though, I could get it working - I think it was because I was passing stopwatchTimerId and stopwatch2TimerId into the function and it may have been passing by reference?
How can I reduce the amount of code repetition here?
var stopwatchTimerId = 0;
var stopwatch2TimerId = 0;
$('#stopwatch').click(function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
clearInterval(stopwatchTimerId);
}
else {
$(this).addClass('active');
stopwatchTimerId = setInterval(function () {
var currentValue = parseInt($('#stopwatch-seconds').val()) || 0;
$('#stopwatch-seconds').val(currentValue + 1).change();
}, 1000);
}
});
$('#stopwatch2').click(function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
clearInterval(stopwatch2TimerId);
}
else {
$(this).addClass('active');
stopwatch2TimerId = setInterval(function () {
var currentValue = parseInt($('#stopwatch2-seconds').val()) || 0;
$('#stopwatch2-seconds').val(currentValue + 1).change();
}, 1000);
}
});
As you can see, it's basically the same code in each except for stopwatchTimerId and $('#stopwatch-seconds') (and the same vars with 2 on it for the other one).
This won't pollute global scope and also you don't need to do any if-else statements. Just add data-selector to your new elements :)
<input id="stopwatch" type="text" data-selector="#stopwatch-seconds"/>
<input id="stopwatch2" type"text" data-selector="#stopwatch2-seconds"/>
$('#stopwatch stopwatch2').click(function () {
var $element = $(this),
interval = $element.data('interval');
selector = $element.data('selector');;
if ($element.hasClass('active')) {
$element.removeClass('active');
if (interval) {
clearInterval(interval);
}
}
else {
$element.addClass('active');
$element.data('interval', setInterval(function () {
var currentValue = parseInt($(selector).val()) || 0;
$(selector).val(currentValue + 1).change();
}, 1000));
}
});
function stopwatch(id){
$('#' + id).click(function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
clearInterval(window[id]);
}
else {
$(this).addClass('active');
window[id] = setInterval(function () {
var currentValue = parseInt($('#' + id + '-seconds').val()) || 0;
$('#' + id + '-seconds').val(currentValue + 1).change();
}, 1000);
}
});
}
$(function(){
stopwatch("stopwatch");
stopwatch("stopwatch2");
});
You could do something like this (code is not very nice, you can improve it):
var stopwatchTimerId;
$('#stopwatch').click(function () {
doStopWatch(1);
});
$('#stopwatch2').click(function () {
doStopWatch(2);
});
var doStopWatch = function(option){
var stopWatch = option===1?$('#stopwatch'):$('#stopwatch2');
if (stopWatch.hasClass('active')) {
stopWatch.removeClass('active');
clearInterval(stopwatchTimerId);
}
else {
stopWatch.addClass('active');
stopwatchTimerId = setInterval(function () {
var currentValue = option===1?(parseInt($('#stopwatch-seconds').val()) || 0):(parseInt($('#stopwatch2-seconds').val()) || 0);
if(option===1)
$('#stopwatch-seconds').val(currentValue + 1).change();
else
$('#stopwatch2-seconds').val(currentValue + 1).change();
}, 1000);
}
}
Try
var arr = $.map($("div[id^=stopwatch]"), function(el, index) {
el.onclick = watch;
return 0
});
function watch(e) {
var id = this.id;
var n = Number(id.split(/-/)[1]);
if ($(this).hasClass("active")) {
$(this).removeClass("active");
clearInterval(arr[n]);
} else {
$(this).addClass("active");
arr[n] = setInterval(function() {
var currentValue = parseInt($("#" + id + "-seconds").val()) || 0;
$("#" + id + "-seconds").val(currentValue + 1).change();
}, 1000);
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="stopwatch-0">stopwatch1</div>
<input type="text" id="stopwatch-0-seconds" />
<div id="stopwatch-1">stopwatch2</div>
<input type="text" id="stopwatch-1-seconds" />

Js and Divs, (even <div> is difference)

I Have find a javascript code that works perfectly for showing a DIV.
but this code works only for showing one div for each page.
i want to include many DIVS for hiding and showing in the same page.
I was try to replace the div id and show/hide span id with a rundom php number for each include, but still is not working.
so how i have to do it?
the JS code:
var done = true,
fading_div = document.getElementById('fading_div'),
fade_in_button = document.getElementById('fade_in'),
fade_out_button = document.getElementById('fade_out');
function function_opacity(opacity_value) {
fading_div.style.opacity = opacity_value / 100;
fading_div.style.filter = 'alpha(opacity=' + opacity_value + ')';
}
function function_fade_out(opacity_value) {
function_opacity(opacity_value);
if (opacity_value == 1) {
fading_div.style.display = 'none';
done = true;
}
}
function function_fade_in(opacity_value) {
function_opacity(opacity_value);
if (opacity_value == 1) {
fading_div.style.display = 'block';
}
if (opacity_value == 100) {
done = true;
}
}
// fade in button
fade_in_button.onclick = function () {
if (done && fading_div.style.opacity !== '1') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout((function (x) {
return function () {
function_fade_in(x)
};
})(i), i * 10);
}
}
};
// fade out button
fade_out_button.onclick = function () {
if (done && fading_div.style.opacity !== '0') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout((function (x) {
return function () {
function_fade_out(x)
};
})(100 - i), i * 10);
}
}
};
Check out the Fiddle, you can edit code based on your needs ;)
$(function() {
$('.sub-nav li a').each(function() {
$(this).click(function() {
var category = $(this).data('cat');
$('.'+category).addClass('active').siblings('div').removeClass('active');
});
});
});
finaly i found my self:
<a class="showhide">AAA</a>
<div>show me / hide me</div>
<a class="showhide">BBB</a>
<div>show me / hide me</div>
js
$('.showhide').click(function(e) {
$(this).next().slideToggle();
e.preventDefault(); // Stop navigation
});
$('div').hide();
Am just posting this in case someone was trying to answer.

function is undefined in firefox only

ok, the following code works ok in IE7+ and Chrome.
but for some reason, xfade is undefined in firefox
<html>
<body>
<div id="slider"></div>
<script type="text/javascript">
var Klimateka = {
Slider: function () {
// Check if we have a slider div on page
var slider = document.getElementById('slider');
if (slider != null) {
var images = ["slide-image-1.jpg", "slide-image-2.jpg", "slide-image-3.jpg", "slide-image-4.jpg"];
var i = images.length;
while (i) {
i -= 1;
var img = document.createElement("img");
img.src = "images/" + images[i];
slider.appendChild(img);
}
var d = document, imgs = new Array(), zInterval = null, current = 0, pause = false;
imgs = d.getElementById("slider").getElementsByTagName("img");
for (i = 1; i < imgs.length; i++) imgs[i].xOpacity = 0;
imgs[0].style.display = "block";
imgs[0].xOpacity = .99;
setTimeout("xfade()", 3500);
function xfade() {
cOpacity = imgs[current].xOpacity;
nIndex = imgs[current + 1] ? current + 1 : 0;
nOpacity = imgs[nIndex].xOpacity;
cOpacity -= .05;
nOpacity += .05;
imgs[nIndex].style.display = "block";
imgs[current].xOpacity = cOpacity;
imgs[nIndex].xOpacity = nOpacity;
setOpacity(imgs[current]);
setOpacity(imgs[nIndex]);
if (cOpacity <= 0) {
imgs[current].style.display = "none";
current = nIndex;
setTimeout(xfade, 3500);
} else {
setTimeout(xfade, 50);
}
function setOpacity(obj) {
if (obj.xOpacity > .99) {
obj.xOpacity = .99;
return;
}
obj.style.opacity = obj.xOpacity;
obj.style.MozOpacity = obj.xOpacity;
obj.style.filter = "alpha(opacity=" + (obj.xOpacity * 100) + ")";
}
}
}
},
bar: function () {
}
};
Klimateka.Slider();
i have setup a jsfiddler for testing:
http://jsfiddle.net/rTtKh/10/
This might only apply to Firefox:
functions do not hoist when declared inside a child block.
You declare xfade inside the if block, but you are calling it prior to the declaration:
setTimeout(xfade, 3500);
Put the function declaration on top.
You have to do the same with setOpacity inside xfade. <- That is not necessary.
Fix your line that says this: setTimeout("xfade()", 3500); to match your others:
setTimeout(xfade, 3500);
Use setTimeout(xfade, 3500) instead.

Javascript Focus() function not working

I have a textbox which I want to set the focus on, but it doesn't work.
document.getElementById("txtCity").focus();
Any idea?
Maybe you are calling the JavaScript before the input element is rendered? Position the input element before the JavaScript or wait until the page is loaded before you trigger your JavaScript.
In that order, it works just fine:
<input type="text" id="test" />
<script type="text/javascript">
document.getElementById("test").focus();
</script>
In jQuery you could place your code within the .ready() method to execute your code first when the DOM is fully loaded:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#test").focus();
// document.getElementById("test").focus();
});
</script>
In case someone searching has a similar situation to mine ... I had to set a tabindex attribute before my div could receive focus():
featured.setAttribute('tabindex', '0');
featured.focus();
console.log(document.activeElement===featured); // true
(I found my answer here: Make div element receive focus )
And of course, make sure the body element is ready before setting focus to a child element.
I have also faced same problem.To resolve this problem, put your code in setTimeout function.
function showMeOnClick() {
// Set text filed focus after some delay
setTimeout(function() { jQuery('#searchTF').focus() }, 20);
// Do your work.....
}
Try to wrap it into document ready function and be sure, that you have jquery included.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#test").focus();
});
</script>
<div id="txtROSComments" contenteditable="true" onkeyup="SentenceCase(this, event)"style="border: 1px solid black; height: 200px; width: 200px;">
</div>
<script type="text/javascript">
function SentenceCase(inField, e) {
debugger;
var charCode;
if (e && e.which) {
charCode = e.which;
} else if (window.event) {
e = window.event;
charCode = e.keyCode;
}
if (charCode == 190) {
format();
}
}
function format() {
debugger; ;
var result = document.getElementById('txtROSComments').innerHTML.split(".");
var finaltxt = "";
var toformat = result[result.length - 2];
result[0] = result[0].substring(0, 1).toUpperCase() + result[0].slice(1);
if (toformat[0] != " ") {
for (var i = 0; i < result.length - 1; i++) {
finaltxt += result[i] + ".";
}
document.getElementById('txtROSComments').innerHTML = finaltxt;
alert(finaltxt);
abc();
return finaltxt;
}
if (toformat[0].toString() == " ") {
debugger;
var upped = toformat.substring(1, 2).toUpperCase();
var formatted = " " + upped + toformat.slice(2);
for (var i = 0; i < result.length - 1; i++) {
if (i == (result.length - 2)) {
finaltxt += formatted + ".";
}
else {
finaltxt += result[i] + ".";
}
}
}
else {
debugger;
var upped = toformat.substring(0, 1).toUpperCase();
var formatted = " " + upped + toformat.slice(1);
for (var i = 0; i < result.length - 1; i++) {
if (i == (result.length - 2)) {
finaltxt += formatted + ".";
}
else {
//if(i
finaltxt += result[i] + ".";
}
}
}
debugger;
document.getElementById('txtROSComments').value = finaltxt;
return finaltxt;
}
</script>
<script type="text/javascript">
function abc() {
document.getElementById("#txtROSComments").focus();
}
It works fine in this example
http://jsfiddle.net/lmcculley/rYfvQ/

Categories