Changing CSS, Text of dynamically loaded content in JS

Hi folks,

At the moment I am working with a single-page-application (SPA) which I found on Medium (JS Vanilla Script SPA by Better Programming/Santiago Garcia da Rosa) and so far it’s fine. But there’s a problem with: I want to manipulate the dynamically loaded content, like modifying texts, change styling and so on. Styling works for the general body, but not the dynamically loaded content. So I need to find a way, but don’t know how as I am not (yet) that good in JS.
The challenge seems to be the structure with the JS-files from the tutorial.

So I have this code and so far it’s fine. But what doesn’t work is changing css and text when I visit the page with the poll-hash, it’s dynamically loaded.

window.addEventListener('hashchange', function(e){
    if(location.hash=='#profile')
    {
      console.log('#profile');
    }
    else if(location.hash=='#cvedit')
    {
      console.log('#cvedit');    
    }
    else if(location.hash=='#poll')
    {
      console.log('#poll');
      $("#question_text").css("color","blue");
      $("#question_text").text("Where's Waldo?");
    }
    else if(location.hash=='#about')
    {
      console.log('#about');

    }
    else if(location.hash='#home')
    {
      console.log('#home');
    }           
})

Thanks in advance for your help.

Note: In my post before editing I had another code. This is why user JanShah is referring to another code. Since them I minimized the source of my problem to the change of dynamically loaded content.

When you say it doesn’t work, what do you mean?
Do you get any errors?
What doesn’t it do?
What does it do?
What do you expect it to do?
if loadPosition calls loadUI, why do you want loadUI to work separately?
Are you sure all the ID’s that you want to populate exist?
You have quite a few conditionals, are you sure they are being followed as you expect?

Have you tried debugging the script using the chrome developer console? Just add the word debugger before or after any part of the code you want to analyse and keep the developer console open. The program will break execution wherever you added debugger and show you a lot of helpful information about the current state of all the local variables. You can step through each line of code and see, step by step, what’s happening when you commit an action.

If you have the site available online, it might be easier to diagnose.

Thanks for reminding me of being more specific.
Do you get any errors? No, I don’t.
What doesn’t it do? loadUI doesn’t change the HTML/text of the elements.
What does it do It shows the messages in the console which I added to see if the function is executed.
What do you expect it to do Generally I expect it to change the HTML based on the c. So if c equals 0, it shows “Employer & Position”. OR: $("#pos_tax").text(“Employer & Position”);
if loadPosition calls loadUI, why do you want loadUI to work separately? In loadPosition I load an existing position, using a set variable. If I create a new position I need to change the UI anyway, but based on the category © which is job or education or a project. And I can say: it works inside loadPosition.
Are you sure all the ID’s that you want to populate exist? Yes, I have checked them (as I am struggling for some days).
You have quite a few conditionals, are you sure they are being followed as you expect? The conditions work as expected. I used some breakpoints in Chrome and it seem to work.

ok.

I’m running the snippet in codepen and it seems ok. I’ve only added a couple of elements and they appear to populate as expected.

https://codepen.io/centropy/pen/VwvKGzo

Unfortunately it’s not solving the problem.

So I do what I should have already done. Sharing the full code.

var c, pid, uid, test;


function paramsToObject(entries) {
  let result = {}
    for(let entry of entries) { 
      const [key, value] = entry;
    result[key] = value;
  }
  return result;
}

function deparam(strinput)
{
  var hex = strinput, 
      bytes = [],
      str;

  for(var i=0; i< hex.length-1; i+=2){
      bytes.push(parseInt(hex.substr(i, 2), 16));
  }

  str = String.fromCharCode.apply(String, bytes);

  const urlParams = new URLSearchParams(str);
  const entries = urlParams.entries(); 
  const params = paramsToObject(entries); 
  console.log(params);
  c = params["pos_type"];
  uid = params["pos_usr"];
  pid = params["pos_id"];
}


window.addEventListener('hashchange', function() {
  if(location.hash=='#cvedit')
  {
    if(localStorage.cvhash)
    {
      deparam(localStorage.cvhash); 
      //alert("deparam");
      if((!pid)&&(c))
      {
        loadUI(c,pid);        
      }
      else if(pid)
      {
        loadPosition(pid,uid,c);              
      }

    }
  }
}, false);



$(document).on('keyup','#entity_url',function(){
        var url = document.getElementById("entity_url").value;             
      console.log(url+' '+c);
        event.preventDefault();
        $.ajax({
          method: 'post',
          asyng: false,
          url: 'controller/controller_entity_check_api.php',
          data: {url:url, enty:c},
          cache:false,
          success: function(response) 
          {
            setTimeout(function(){                  
                  var repo = JSON.parse(response);
                  console.log(repo);
                  if ((repo["status"]==0) && (url.indexOf('.') !== -1)){   
                       //$('#entityname').prop("disabled",false);
                      $('#entityname').prop("readOnly",false); 
                      $('#prof_entity_id').val('');                     
                  }
                  else if ((repo["status"]==0) && (url.indexOf('.') == -1)){   
 
                      //$('#entityname').prop("disabled",true);
                      $('#entityname').prop("readOnly",true);                         
                  }
                  else{   
                      
                      //var webs = repo["data"]["website"];
                      if(repo["status"]==1)
                      {
                        var nme = repo["data"]["name"];
                        var cid = repo["data"]["id"]; 
                        console.log(cid);           
                        $('#entityname').val(nme);
                        $('#entity_field').val(nme);
                        company_name = repo["data"]["name"];
                        $('#prof_entity_id').val(cid);
                        //$('#entityname').prop("disabled",true);
                        $('#entity_field').html(company_name);
                        $('#entityname').prop("readOnly",true);                         
                        $('#prof_btn_add').prop('disabled',false);                          
                      }
                  }
            },500);
          }                 
        });  
})


$(document).on('change keyup focus','#position_entity', function() {
      $('#position').html($(this).val());
})

$(function() {
//SHOW ELEMENTS
$('#position_entity').on('change keyup focus',function() {
    $('#position').html($(this).val());
});

$('#entityname').on("change paste keyup",function() {
      $('#entity_field').html($(this).val());
  });
});

function getCountry() {
  $.ajax({
    type: "GET",
    url: "controller/controller_country_api.php",
    success: function(data){
      $("#position_country").append(data);
    }
  });
}

function getState(val,val2) {
  $.ajax({
    type: "POST",
    url: "controller/controller_state_api.php",
    data:{country_id: val, state: val2},
    success: function(data){
      $("#position_state").html(data);
    }
  });
}
$(document).on('change','select#position_country', function() {
      getState(this.value);
      $("#position_state").prop("disabled",false);
})
getCountry();


$(document).on('change','#position_country',function(){
      if ( $(this).children(":selected").val() === "" ) {
        $('#position_state').prop('disabled', true);
        $('#position_city').prop('disabled', true);   
      }
      else
      { 
        $('#position_state').prop('disabled', false);
        $('#position_city').prop('disabled', false);   
      }    
})



$(document).on('change','#position_state',function(){
      if ( $(this).children(":selected").val() === "" ) {
        $('#position_city').prop('disabled', true);   
      }
      else
      { 
        $('#position_city').prop('disabled', false);   
      }        
})



$(document).on('change','#curworkhere_prof',function(){

        console.log("cvedit");
        if (this.checked) {
            $('#enddate_prof').prop('disabled', true);
        }
        else
        {
            $('#enddate_prof').prop('disabled', false);         
        }
});



$(document).on('change keyup focus','#position_country',function(){
    if($('#position_country').val().length > 0)
    {
      $('#loc_country').html($('#position_country').find("option:selected").text()); 
      
      $('#position_state').on('change keyup focus',function() {
          if($('#position_state').val().length > 0)
          {
            $('#loc_state').html($('#position_state').find("option:selected").text());
            $("#loc_state").append(", "); 
            
            $('#position_city').on('change keyup focus',function() {
                if($('#position_city').val().length > 0)
                {
                  $('#loc_city').html($('#position_city').val());
                  $("#loc_city").append(", ");      
                }
                else
                {
                  $('#loc_city').empty();  
                }
            });                
          }
          else
          {
            $('#loc_state').empty();          
          }
      });           
    }
    else 
    {
      $('#loc_country').empty();
      $('#loc_state').empty();
      $('#loc_city').empty();
    }  
})


$(document).on('change keyup focus','#enddate_prof',function(){
    $('#date_end').html($(this).val());  
});

$(document).on('change keyup focus','#startdate_prof',function(){
    $('#date_start').html($(this).val());  
});


//WORK END

function loadPosition(pid,uid,c)
{
  if(pid)
  { 
    $.ajax({
      method: 'post',
      url: 'controller/controller_cv_position_api.php',
      data: {
        pid:pid,uid:uid,c:c, op:'read'
      },
      cache:false,
      success:function(data) 
      {
        var get_cv_data = JSON.parse(data);
        //debugger
        console.log(get_cv_data["data"]);
        var cv_pos_id = get_cv_data["data"]["cv_pos_id"];
        var cv_comp_id = get_cv_data["data"]["cv_comp_id"];
        var cv_pos_cat = get_cv_data["data"]["cv_pos_cat"];
        var cv_website = get_cv_data["data"]["cv_website"];
        var cv_name = get_cv_data["data"]["cv_name"];
        var cv_city = get_cv_data["data"]["cv_city"];
        var cv_state = get_cv_data["data"]["cv_state"];
        var cv_state_name = get_cv_data["data"]["cv_state_name"];
        var cv_country = get_cv_data["data"]["cv_country"];
        var cv_position = get_cv_data["data"]["cv_position"];
        var cv_start = get_cv_data["data"]["cv_start"];
        var cv_end = get_cv_data["data"]["cv_end"];
        var cv_degree = get_cv_data["data"]["cv_degree"];

        $('#prof_jobid').val(cv_pos_id);
        $('#prof_entity_id').val(cv_comp_id); 
        $('#entitytype').val(cv_pos_cat);                               

        $('#entity_url').val(cv_website);
        $('#entityname').val(cv_name);

        $('#position_entity').val(cv_position);
        $('#startdate_prof').val(cv_start);

        $('#prof_entity').val(data.company);
         //DISPLAY
         $('#position').html(cv_position);
         $('#entity_field').html(cv_name);

         //DISPLAY DATE
         $('#date_start').html(cv_start);
         if(cv_end== null)
         {
          $('#date_end').html("present");
         }
         else
         {
          $('#date_end').html(cv_end);                    
         }


         //DISPLAY LOCATION
         if(cv_country.length > 0)
         {
          $('#loc_country').html(cv_country);
          if(cv_state.length > 0)
          {
            $('#loc_state').html(cv_state_name);
            $("#loc_state").append(", ");
            if(cv_city.length > 0)
            {
              $('#loc_city').html(cv_city);               
              $("#loc_city").append(", ");                         
            }                      
          } 
         }

         //CV COUNTRY
         if(!cv_country){
          $('#position_country option[value="0"]').prop('selected',true);
         }
         else {
          $('#position_country option[value="'+cv_country+'"]').prop('selected',true);                
          getState(cv_country,cv_state);  
         }
          //CV STATE
          if(!cv_state){
            $('#position_state option[value="0"]').prop('selected',true);  
            $('#position_state').prop('disabled',true);                                    
          }
          else {
            $('#position_state option[value="'+cv_state+'"]').prop('selected',true);
            $('#position_state').prop('disabled',false);
            if(!cv_city){
              $('#position_city').prop('disabled',true);                                               
            }
            else{
              $('#position_city').val(cv_city);  
              $('#position_city').prop('disabled',false);                         
            }
          }               
          //CV DEGREE
          if(cv_degree == null){
            $('#edu_degree option[value="0"]').prop('selected',true);                
          }
          else {
            $('#edu_degree option[value="'+cv_degree+'"]').prop('selected',true);                
          }
          $('#prof_btn_update').css("display", "inline");
          $('#prof_btn_clear').css("display", "inline");
          $('#prof_btn_update').prop('disabled', false);
          $('#prof_btn_clear').prop('disabled', false);              
          $('#prof_btn_add').css("display", "none");
          if (cv_end == null){
            $('#curworkhere_prof').prop('checked',true);
            $('#enddate_prof').prop('disabled', true);
            $('#enddate_prof').val(''); 

            $('#curworkhere_prof').prop('checked', true);
          }
          else {
            $('#enddate_prof').val(cv_end);
            $('#curworkhere').prop('checked',false);
            $('#enddate_prof').prop('disabled', false);

            $('#curworkhere_prof').prop('checked', false);                                                                             
          }
          loadUI(c,pid);
      }
    });
  } 
}


function loadUI(c,pid)
{
  if(c)
  {
        console.log("c is "+c);
        if(c=="0")
        {
            $("#area_title").html("Professional Experience");
            
            $('#ent_url_label').html("Company URL");    
            $('#ent_name_label').html("Company Name");     
            $('.sel_btn').removeClass('disabled');
            $('#prof').addClass('disabled');
            $('#entity_posi_next').css('display','none'); //degrees
            $('#position_label').html('Position'); 
            $('#prof_posi_prev').removeClass('col-md-6').addClass('col-md-12');
            $('#entitytype').val('0'); 
            $('#curworkhere_prof_label').html("I currently work here!");
            $("#pos_tax").text("Employer & Position");
            console.log("pos tax");
            if(pid)
            {
              $('#pos_title').html("Editing Job Entry");
              console.log("pid input");    
            }
            else
            {
              $('#pos_title').html("Creating Job Entry");
                          console.log("no pid");       
            }            
        }
        else if(c=="1")
        {
          $('#area_title').html('Education');
          $('#ent_url_label').html("College URL");    
          $('#ent_name_label').html("College Name");    
          $('.sel_btn').removeClass('disabled');
          $('#edu').addClass('disabled');
          $('#entity_posi_next').css('display','block');
          $('#position_label').text('Major');
          $('#prof_posi_prev').removeClass('col-md-12').addClass('col-md-6'); 
          $('#entitytype').val('1');
          $('#curworkhere_prof_label').html("I currently study here!");  
          $('#pos_tax').html("Institution & Major");
          if(pid)
          {
            $('#pos_title').html("Editing Academic Entry");   
          }
          else
          {
            $('#pos_title').html("Creating Academic Entry");        
          }                                       
        }
        else if(c=="2")
        {
          $('#area_title').html("Project");
          $('#ent_url_label').html("Project URL");    
          $('#ent_name_label').html("Project Name"); 
          $('.sel_btn').removeClass('disabled');
          $('#proj').addClass('disabled');
          $('#entity_posi_next').css('display','none');
          $('#position_label').html('Position'); 
          $('#prof_posi_prev').removeClass('col-md-6').addClass('col-md-12');
          $('#entitytype').val('2');
          $('#curworkhere_prof_label').html("I currently work here!");     
          $('#pos_tax').html("Employer & Position");
          if(pid)
          {
            $('#pos_title').html("Editing Project Entry");    
          }
          else 
          {
            $('#pos_title').html("Creating Project Entry");       
          }                                       
        }     
  }
}

This is the code without your suggested edit of course, showing you the original code I use.

I haven’t suggested any edits.
The code helps but if loadUI is causing the problem, it’s the only one that requires analysis.

I’ve copied all the code over to codepen and ran loadUI with a single dom element, using argument ‘1’ and true. I’m sure it does exactly what you expect it to do. https://codepen.io/centropy/pen/rNOMqyE

Without a full view of the interaction I’m struggling to see the issue.

I found out where the problem really is. It’s the dynamically loaded stuff. Maybe you can look on my edited post with new description?