$(window).bind("load") and $(element).html in pure javascript - javascript

I am trying to change this jquery to pure javascript:
var subContainerElement = $('#' + mainContainerId).find('#' + subContainer);
$(window).bind("load", function () {
$(subContainerElement).html(function (index, text) {
newParagraphText = text.replace("aaa", "bbb");
return newParagraphText;
});
});
Javascript:
var subContainerElement = mainContainer.getElementsByClassName(subContainer)[0];
document.addEventListener("DOMContentLoaded", function(event) {
mainContainer.getElementsByClassName(subContainer)[0].innerHTML =
function (index, text) {
newParagraphText = text.replace("aaa", "bbb");
return newParagraphText;
};
});
Unfortunately, the innerHTML function set the html of the element to be:
function (index, text) { ......
Any help appreciated.

In the jQuery based code, you're looking for an element whose id is subContainer.
Assuming it works, the second one should be
var subContainerElement = document.getElementById(subContainer);
document.addEventListener("DOMContentLoaded", function(event) {
var html = subContainerElement.innerHTML;
html = html.replace("aaa", "bbb");
subContainerElement.innerHTML = html;
});
Note that the first code is very bad, with a very strange element selection and an undeclared variable.

Related

Looking to modify href based on click and AddEventListener

I'm trying to modify a URL based on the user either (or both) clicking one of 3 text links and/or entering a keyword into a text input. Currently, I have it working, but doing both overwrites the other. For example, if I click on "Scholarships," it looks good. If I enter a word into the text input, it works but overwrites my previous selection. Please be kind, as I'm new to JS.
A CodePen:
https://codepen.io/admrbsn/pen/QOQmMN
My JS:
$(document).ready(function () {
var select = $('.custom-option');
var input = document.querySelector("#search-input");
select.click(function(e) {
var type = e.target.getAttribute('data-value');
var link = "/search/" + type + "/?searchterm=";
document.querySelector('#searchLink').href = link;
});
input.addEventListener("change", function() {
var keyword = this.value;
var link = "/search/?searchterm=" + keyword;
document.querySelector('#searchLink').href = link;
});
});
Try to reuse code, for example create a function that updates the link from both actions.
example:
function updateLink() {
var href = '';
if (link)
href = "/search/" + link + "/?searchterm=" + text;
else
href = "/search/?searchterm=" + text;
document.querySelector('#searchLink').href = href;
}
complete example:
https://codepen.io/anon/pen/ooEywW
Well yes, the change event is firing and is running the second block of code (input.addEventListener("change", function() {) that sets it without the type. I'd recommend setting variables outside of those events, and then changing the HREF with a separate code block:
$(document).ready(function () {
var select = $('.custom-option');
var input = document.querySelector("#search-input");
var type = '';
var searchterm = '';
var updateLink = function () {
var link = "/search/" + type + "?searchterm=" + searchterm;
document.querySelector('#searchLink').href = link;
}
select.click(function(e) {
type = e.target.getAttribute('data-value');
updateLink();
});
input.addEventListener("change", function() {
searchterm = this.value;
updateLink();
});
});
Also I'm not sure why you're using document.querySelector when you're already using jQuery. Why not just do $("#search-input")?

html() function with variables

I'm attempting to inject some html code with variables in it into a JQM UL Listview. The problem I am running into is it seems the variables are throwing off the code because when I remove them, it injects the HTML perfectly.
Here is the snippet:
$(document).on("pageinit", "#vendorMessages", function() {
var listView = "";
pubnub.subscribe(
{
channelGroup: getChannelGroup()
},
function (status, response) {
alert("test");
console.log(status, response);
}
);
pubnub.channelGroups.listChannels(
{
channelGroup: getChannelGroup()
},
function (status, response) {
response.channels.forEach( function (channel) {
var channelFormatted = String(channel).split("_");
var channelMember = channelFormatted[1];
var temp = "<li onClick='loadChannel("+channel+")'>"+channelMember+"</li>";
var temp = String(temp);
listView = listView.concat(temp);
})
alert(listView);
}
)
var elem = $("#channels");
elem.html(elem.text(listView));
$("#channels").listview("refresh");
})
The alert(listView) returns the correct string format but the code still will not get added to the <ul>. I've tried a few suggested things, even switching back to javascript innerHTML but no avail. Any thoughts?
Change
elem.html(elem.text(listView));
to
elem.html(listView);
elem.text cannot handle html..

Changing text inside of a dynamically created element

I want to change the text inside of an element for dynamically created elements. i = 2 because that's Why is it not working?
var loanName = function() {
for(var t=1; t < i; t++) {
$('body').on('keyup', '.loanNameV'+t, function () {
var loanN = $('.loanNameV'+t).val();
$('.nameLoan'+t).text(loanN);
});
}
};
$('body').on('keyup', '[class^="loanNameV"]', function () {
var numbesideclass = ($(this).attr('class').split('loanNameV'))[1];
var loanN = $(this).val();
$('.nameLoan'+numbesideclass).text(loanN);
});
Note: this code will work if you don't have another class for loanNameV elements like class="loanNameV1 anotherclass anotherclass" in this case this code will not work as expected

How can i optimize my Jquery code?

I've created some JavaScript using Jquery, for the page animation :
I trying to optimize it since i repeat the same thing for subtab1, subtab2, subtab3.
The same function is executed for all of them, and the only thing is changes is variable i iterating on?
Any suggestion?
<script type="text/javascript">
$(document).ready(function () {
var $defensivo = $('#defensivoimg');
var $equilibrado = $('#equilibradoimg');
var $activo = $('#activoimg');
var $defensivoSubTab = $('#subtab1');
var $equilibradoSubTab = $('#subtab2');
var $activoSubTab = $('#subtab3');
var $fundosdiponiveis = $('#fundosdiponiveis');
var $fundosdiponiveisTab = $('#tabs1');
$defensivo.live('click', function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
$defensivoSubTab.removeClass("hide");
$defensivoSubTab.show();
});
$equilibrado.live('click', function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
$equilibradoSubTab.removeClass("hide");
$equilibradoSubTab.show();
});
$activo.live('click', function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
$activoSubTab.removeClass("hide");
$activoSubTab.show();
});
});
</script>
For a while:
var $fundosdiponiveis = $('#fundosdiponiveis');
This is my default div.
var $defensivoSubTab = $('#subtab1');
var $equilibradoSubTab = $('#subtab2');
var $activoSubTab = $('#subtab3');
That divs apears when i clicking on one of the following tabs:
var $defensivo = $('#defensivoimg');
var $equilibrado = $('#equilibradoimg');
var $activo = $('#activoimg');
And that button hides and changes style"display" to none, on click, of my three #subtab's
var $fundosdiponiveisTab = $('#tabs1');
Any suggestion?
You could write a function that returns the proper function:
function createShowTabFunc(tab) {
return function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
tab.removeClass("hide");
tab.show();
}
}
Then assign your click handlers:
$defensivo.live('click', createShowTabFunc($defensivoSubTab));
$equilibrado.live('click', createShowTabFunc($equilibradoSubTab));
$activo.live('click', createShowTabFunc($activoSubTab));
Have a common class attribute to all the tab's and you just need to write $('.class').click() and in this get the id of the corresponding tab and according to the id fetched by attr function, you can have an if else to define your variables inside the if else and execute your code block.

JQuery .hover / .on('mouseleave') not functioning properly

I am trying to use the hover function which is pretty rudimentary, but I can't seem to get the mouseout/mouseleave to function properly.
Code:
$(document).ready(function(){
$('.SList').css('display','none');
$(".MList a").on('mouseenter',
function(){
var HTMLArr = $(this).children().html().split(':');
$(this).children('p').replaceWith('<p>'+HTMLArr[0]+':&nbsp◤</p>');
$(this).siblings('.SList').slideDown('slow');
})
.on('mouseleave',function(){
var HTMLArr = $(this).children().html().split(':');
$(this).children('p').replaceWith('<p>'+HTMLArr[0]+':&nbsp◢</p>');
$(this).siblings('.SList').slideUp('slow');
});
});
The mouseenter works properly, but it is not even entering the code for the mouseleave. Any ideas would be greatly appreciated.
Fiddle
See this: DEMO
$(".MList a").on('mouseenter',
function(){
var HTML = $(this).children('p').html();
$(this).children('p').html(HTML.replace('◢','◤'));
$(this).siblings('.SList').slideDown('slow');
})
.on('mouseleave',function(){
var HTML = $(this).children('p').html();
$(this).children('p').html(HTML.replace('◤','◢'));
$(this).siblings('.SList').slideUp('slow');
});
You have an issue with the anchor of the event.
Change to use this:
$(".MList a").on('mouseenter', function () {
var myP = $(this).children('p');
var HTMLArr = myP.text().split(':');
myP.html( HTMLArr[0] + ':&nbsp◤');
$(this).next('.SList').slideDown('slow');
}).on('mouseleave', function () {
var myP = $(this).children('p');
var HTMLArr = myP.text().split(':');
myP.html( HTMLArr[0] + ':&nbsp◢');
$(this).next('.SList').slideUp('slow');
});
You have the same issue with click, and redo same thing. SO, rework and reuse: (you could even make it better but this shows the start of that)
$(".MList a").on('mouseenter', function () {
down($(this).find('p').eq(0));
}).on('mouseleave', function () {
up($(this).find('p').eq(0));
});
$(".MList a").click(function () {
if ($(this).siblings('.SList').is(':visible')) {
up($(this).find('p').eq(0));
} else {
down($(this).find('p').eq(0));
}
});
function up(me) {
var HTMLArr = me.text().split(':');
me.html(HTMLArr[0] + ':&nbsp◢');
me.parent().next('.SList').slideUp('slow');
}
function down(me) {
var HTMLArr = me.text().split(':');
me.html(HTMLArr[0] + ':&nbsp◤');
me.parent().next('.SList').slideDown('slow');
}

Categories

Resources