In my react web, I have a script tag with functions inside shown below (like: clicking on button changing class name and so on...). I want to know how to convert the functions inside the script tag to React JS. Please Help Thank you!
/* tab */
function tab(e, num) {
var num = num || 0;
var menu = $(e).children();
var con = $(e + "_con").children();
var select = $(menu).eq(num);
var i = num;
select.addClass("on");
con.eq(num).show();
menu.click(function () {
if (select !== null) {
select.removeClass("on");
con.eq(i).hide();
}
select = $(this);
i = $(this).index();
select.addClass("on");
con.eq(i).show();
});
}
/* Function */
$(function () {
/* tab */
tab("#tab", 0);
tab("#tab_bg", 0);
/* 기본 배경 click */
$(".btn_bg").on("click", function () {
$(".btn_bg.on")
.find("img")
.attr(
"src",
$(".btn_bg.on")
.find("img")
.attr("src")
.replace("_on.svg", "_off.svg")
);
$(".btn_bg").removeClass("on");
var thisImg = $(this).find("img");
thisImg.attr(
"src",
thisImg.attr("src").replace("_off.svg", "_on.svg")
);
$(this).addClass("on");
});
as I can see your code is mostly jquery based, wich have no sense to migrate.. in any case you can refactorize your code to a react version
Related
I have searched for an answer for this and I understand how event delegation works but what ever I try nothing changes.
The buttons that are dynamicaly created will not trigger the on event when manually clicked however using the trigger() method works, what is wrong with my code?
components.forEach(function (component) {
var id = randomId();
var li = $.create("li").addClass("col-12");
componentList.append(li);
var btn = $.create("button")
.text(component.type)
.attr("id", id)
.addClass("btn")
.appendTo(li);
componentList.on("click", "#" + id, function () {
alert("test");
window.circuit.push(component.create());
circuitList.refresh();
});
btn.trigger("click");
});
$.create = function (arg) {
return $(document.createElement(arg));
}
randomId = function () {
return "id" + Math.floor(Math.random() * 100000) + "_" + Math.floor(Math.random() * 100000);
}
The display is as expected, the buttons just won't fire manually.
Components is an array of objects with a type property and create method.
The following statement was erroneous:
componentList.on("click", "#" + id, function () {...
jQuery is smart enough to know which button was clicked just by using a class or even a tag as the second parameter.
$('.list').on("click", '.btn', function(e) {
Details commented in Demo
Demo
/* Had no idea what components is supposed to be */
var components = ['potentiometer', 'transistor', 'capicitor', 'transformer'];
/* On each loop $.map() will run a function */
$.map(components, function(cmp, idx) {
var ranID = randomId();
/* Creating nodes is easy with jQuery
|| You can actually assign a string to a
|| jQuery object and when used with a jQuery method
|| it would be parsed into real HTML
*/
var li = $('<li class="col-12"></li>');
$('.list').append(li);
/* This string is a Template Literal. a TL is a
|| string with a powerful syntax.
*/
var btn = $(`<button id='${ranID}' class='btn' type='button'>${cmp}</button>`);
btn.appendTo(li);
});
/* Originally the OP has a dynamically generated
|| id as the 'this', that's wrong and pointless.
|| That second parameter should be a class ex. '.btn'
*/
$('.list').on("click", '.btn', function(e) {
var ID = $(this)[0].id;
$(`<label for="${ID}"> ${ID}</label>`).insertAfter($(this));
console.log(ID);
alert(`ID:${ID} Type: ${this.textContent}`);
});
function randomId() {
return "id" + Math.floor(Math.random() * 100000) + "_" + Math.floor(Math.random() * 100000);
}
<ol class='list'></ol>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I created a side menu in css and want to use the the tranform: translateX() property to slide it on and off on the page. I'm using a checkbox to toggle the menu on and off. So I thought I can use javascript to make it function, but it's not working. Can you edit the transform property through javascript?
here's the code...
window.onload = function () {
var toggle_btn = document.getElementById('toggle_btn');
var slide_menu = document.getElementById('slide_menu');
var checked = function() {
toggle_btn.checked = true;
};
if (checked === true) {
slide_menu.style.transform = "translateX(0px)";
} else {
slide_menu.style.transform = "translateX(-200px)";
}
};
Try:
window.onload = function () {
var toggle_btn = document.getElementById('toggle_btn'),
slide_menu = document.getElementById('slide_menu');
slide_menu.style.transform = toggle_btn.checked=== true ? "none" : "translateX(-200px)";
};
BTW - you don't need javascript for this: http://jsfiddle.net/w5te8qqx/1/
I'm doing some HTML prototyping to explore some UX stuff. Whilst trying to work out why a Javascript function (which uses a lot of jQuery) wasn't working I broke it out into a JS Fiddle. It seems that when the function is called on document.ready it won't work and can't be executed with a click event. However, if it isn't called at document.ready then it will work! I'm probably missing something obvious...
Working: http://jsfiddle.net/NWmB5/
$(document).ready(function() {
$('#targetFirstDiv').click(function() {
setTimelinePosition($('#anotherDiv'));
});
$('#targetSecondDiv').click(function() {
setTimelinePosition($('#testDiv'));
});
});
var toDoCategories = [$("#testDiv"),$("#anotherDiv")];
/* Show current position on timeline */
function setTimelinePosition($position) {
var $theTimelineTrigger = $('span.timelineTrigger');
toDoCategories.forEach(function(currentCategory) {
var $deselectTimelinePositionElement = $(currentCategory, $theTimelineTrigger);
$($deselectTimelinePositionElement).removeClass('currentPosition');
});
var $selectTimelinePositionElement = ($($position,$theTimelineTrigger));
$($selectTimelinePositionElement).addClass('currentPosition');
}
Not Working: http://jsfiddle.net/NWmB5/5/
$(document).ready(function() {
setTimelinePosition($('#thirdDiv'));
$('#targetFirstDiv').click(function() {
setTimelinePosition($('#anotherDiv'));
});
$('#targetSecondDiv').click(function() {
setTimelinePosition($('#testDiv'));
});
});
var toDoCategories = [$("#testDiv"),$("#anotherDiv"),$("thirdDiv")];
/* Show current position on timeline */
function setTimelinePosition($position) {
var $theTimelineTrigger = $('span.timelineTrigger');
toDoCategories.forEach(function(currentCategory) {
var $deselectTimelinePositionElement = $(currentCategory, $theTimelineTrigger);
$($deselectTimelinePositionElement).removeClass('currentPosition');
});
var $selectTimelinePositionElement = ($($position,$theTimelineTrigger));
$($selectTimelinePositionElement).addClass('currentPosition');
}
You trying to get $("#testDiv"),$("#anotherDiv"),$("thirdDiv") before DOM ready event fired that's where the exact problem.Try after DOM ready fired
var toDoCategories = [$("#testDiv"),$("#anotherDiv"),$("thirdDiv")];
So get $("#testDiv"),$("#anotherDiv"),$("thirdDiv") after DOM ready event dispatched.
var toDoCategories; //NOTE HERE
$(document).ready(function() {
toDoCategories = [$("#testDiv"),$("#anotherDiv"),$("thirdDiv")]; //NOTE HERE
setTimelinePosition($('#thirdDiv'));
$('#targetFirstDiv').click(function() {
setTimelinePosition($('#anotherDiv'));
});
$('#targetSecondDiv').click(function() {
setTimelinePosition($('#testDiv'));
});
});
/* Show current position on timeline */
function setTimelinePosition($position) {
var $theTimelineTrigger = $('span.timelineTrigger');
toDoCategories.forEach(function(currentCategory) {
var $deselectTimelinePositionElement = $(currentCategory, $theTimelineTrigger);
$($deselectTimelinePositionElement).removeClass('currentPosition');
});
var $selectTimelinePositionElement = ($($position,$theTimelineTrigger));
$($selectTimelinePositionElement).addClass('currentPosition');
}
I'm fairly new to jQuery and I'm using the script below. Basically it uses two unordered lists to create tab functionality (one for tabs, one for content). Right now when you click through the tabs, the output is switched from "display:list-item;" to "display:none;". I'm trying to change this to "position:absolute;left:-10000px;" and "position:relative;left:0;" so that all the content gets rendered but just moves off the page rather than be hidden.
I'm having the issue you see at the bottom of the page here http://jqueryui.com/demos/tabs/ except it's not being controlled in the CSS. It's being controlled in the script below somehow that I'm unfamiliar with. Any help would be appreciated.
//INITIALIZATION
$.featureList(
$(".tabs li a"),
$(".output > li"), {
start_item : 0
}
);
//SCRIPT
(function($) {
$.fn.featureList = function(options) {
var tabs = $(this);
var output = $(options.output);
new jQuery.featureList(tabs, output, options);
return this;
};
$.featureList = function(tabs, output, options) {
function slide(nr) {
if (typeof nr == "undefined") {
nr = visible_item + 1;
nr = nr >= total_items ? 0 : nr;
}
tabs.removeClass('current').filter(":eq(" + nr + ")").addClass('current');
output.stop(true, true).filter(":visible").fadeOut();
output.filter(":eq(" + nr + ")").fadeIn(function() {
visible_item = nr;
});
}
var options = options || {};
var total_items = tabs.length;
var visible_item = options.start_item || 0;
options.pause_on_hover = options.pause_on_hover || true;
options.transition_interval = options.transition_interval || 0;
output.hide().eq( visible_item ).show();
tabs.eq( visible_item ).addClass('current');
tabs.click(function() {
if ($(this).hasClass('current')) {
return false;
}
slide( tabs.index( this) );
});
if (options.transition_interval > 0) {
var timer = setInterval(function () {
slide();
}, options.transition_interval);
if (options.pause_on_hover) {
tabs.mouseenter(function() {
clearInterval( timer );
}).mouseleave(function() {
clearInterval( timer );
timer = setInterval(function () {
slide();
}, options.transition_interval);
});
}
}
};
})(jQuery);
The action in that script is happening with .FadeIn and .Fadeout, which animate opacity. Fadeout applies display:none at the end of the opacity animation. Correspondingly, FadeIn only works on elements that are set to display:none. Fadein just won't work on visibility: hidden or opacity:0. Check out the jquery documentation, it's mostly pretty good.
So you want to substitute a css position change for those two lines of code. There are a bunch of different ways to do this, depending mostly on whether or not you want the elements to animate off the page of just leap there.
Also FYI The easiest way to share this sort of stuff for troubleshooting is to make a jsfiddle with a reduced subset of your code, just the relevant stuff, and then everybody can poke away at it until it works. :)
I have some jQuery plugin that changes some elements, i need some event or jQuery plugin that trigger an event when some text input value changed.
I've downloaded jquery.textchange plugin, it is a good plugin but doesn't detect changes via external source.
#MSS -- Alright, this is a kludge but it works:
When I call boxWatcher() I set the value to 3,000 but you'd need to do it much more often, like maybe 100 or 300.
http://jsfiddle.net/N9zBA/8/
var theOldContent = $('#theID').val().trim();
var theNewContent = "";
function boxWatcher(milSecondsBetweenChecks) {
var theLoop = setInterval(function() {
theNewContent = $('#theID').val().trim();
if (theOldContent == theNewContent) {
return; //no change
}
clearInterval(theLoop);//stop looping
handleContentChange();
}, milSecondsBetweenChecks);
};
function handleContentChange() {
alert('content has changed');
//restart boxWatcher
theOldContent = theNewContent;//reset theOldContent
boxWatcher(3000);//3000 is about 3 seconds
}
function buttonClick() {
$('#theID').value = 'asd;lfikjasd;fkj';
}
$(document).ready(function() {
boxWatcher(3000);
})
try to set the old value into a global variable then fire onkeypress event on your text input and compare between old and new values of it. some thing like that
var oldvlaue = $('#myInput').val();
$('#myInput').keyup(function(){
if(oldvlaue!=$('#myInput').val().trim())
{
alert('text has been changed');
}
});
you test this example here
Edit
try to add an EventListner to your text input, I don't know more about it but you can check this Post it may help
Thanks to #Darin because of his/her solution I've marked as the answer, but i have made some small jQuery plugin to achieve the same work named 'txtChgMon'.
(function ($) {
$.fn.txtChgMon = function (func) {
var res = this.each(function () {
txts[0] = { t: this, f: func, oldT: $(this).val(), newT: '' };
});
if (!watchStarted) {
boxWatcher(200);
}
return res;
};
})(jQuery);
var txts = [];
var watchStarted = false;
function boxWatcher(milSecondsBetweenChecks) {
watchStarted = true;
var theLoop = setInterval(function () {
for (var i = 0; i < txts.length; i++) {
txts[i].newT = $(txts[i].t).val();
if (txts[i].newT == txts[i].oldT) {
return; //no change
}
clearInterval(theLoop); //stop looping
txts[i].f(txts[i], txts[i].oldT, txts[i].newT);
txts[i].oldT = $(txts[i].t).val();
boxWatcher(milSecondsBetweenChecks);
return;
}
}, milSecondsBetweenChecks);
}